Welcome to Lesson 6!


Learning Objectives for Today's Lesson

By the end of today's lesson, you should know...
  • What is abstraction?
  • What is the rationale for object-oriented programming?
  • How do you declare a class?
  • How do you declare instance variables?
  • How do you define and call simple instance methods?
  • How do you store object types in an ArrayList?
  • What is method overloading?


1. Classes and Objects

Introduction to Classes and Objects

  • Java programs are constructed from objects that interact with each other
  • Because of this, Java is known as an object-oriented programming language
  • Therefore, when you program in Java you focus on objects

Why Objects?

  • If you look around you, how would you summarize what you see in one word?
  • In programming terms, that one word is:
  • Object: a person, place or thing that either performs some action in a situation or is acted upon

  • Each object has certain characteristics, like color or number of appendages
  • Also, each object has behaviors, which are the things it can do
  • For example, a car has characteristics such as color and four wheels
  • Also, a car has behaviors such as accelerating and braking
  • As humans we are use to working with objects in the real world
  • We know how to reason about objects and solve problems with objects

Abstraction

  • In object oriented programs, we use our ability to work with objects to solve software problems
  • However, when we develop software we have to make things simpler than in the real world
  • How do we simplify without losing the essence of the object?
  • We can simplify using a concept called abstraction
  • Abstraction: removing inessential features, until only the relevant parts of the concept remain
  • How does the below image relate to the idea of an abstraction? How does the veterinarian see the cat compared to how the cat's companion sees the cat?

mira2

Software Objects

  • To describe a software object, we write code for storing data and taking actions
  • We need to use the idea of abstraction, because there is no means of taking an object from the real world and flattening it into a piece of code.
  • Instead, we select certain (useful) attributes of the object to describe in our code.
  • We write all the code describing an object in a single software construct called a class

    Class: a software construct that is used as a blueprint to create objects.

  • We use the word class because a class defines a type of (or kind of, or class of) object
  • In a class, data is defined by variables (fields) and the actions are performed in methods
  • Each object can have different data but each object of a class has the same type of data and the same methods
  • A class describes an object but is not the object itself
  • From classes we construct objects for our programs
  • Objects are usually referred to as an object of a class or as an instance of a class
  • In the following sections we look at how to code classes that construct objects

Video Describing Classes and Objects


Declaring a Class

  • The general syntax for writing a class is:
    [accessModifier] class ClassName {
        // fields, constructors, and methods of the class
    }
    
  • Where:
    • accessModifier: controls which classes can access this class
    • ClassName: the name you make up for the class
  • For now, use the access modifier: public
  • The public access modifier means all other classes can use this class
  • Later on we will discuss why you might chose another modifier
  • Note that the ClassName is capitalized by convention
  • The curly braces encapsulates all the fields, constructors, and methods of the class
  • You can see the modifiers, names and other features in the following example
  • Note that this example class is overly simplistic but gives us a starting point

Class Declaration -- First Attempt

1
2
3
4
5
6
7
8
9

public class Phone {
    public String brand;
    public String model;
    public double price;

    public void makeCall() { System.out.println(brand + " is now making a call."); } }

Testing the Class

  • To run the example class we typically write another class for testing
  • We can start with a simple main() method that instantiates two objects, assigns values to variables and calls a method

Test Class for Class Declaration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

public class PhoneTest {
    public static void main(String[] args) {
        Phone iphone = new Phone();
        iphone.brand = "iPhone";
        iphone.model = "7S";
        iphone.price = 521.56;

        Phone samsung = new Phone(); samsung.brand = "Samsung"; samsung.model = "Galaxy S8"; samsung.price = 499.99;
        
iphone.makeCall();         samsung.makeCall(); } }

Instance Variables

  • Recall the following two lines from the class declaration:
    public String brand;
    public double price;
    
  • These variables are known as instance variables, member variables or fields:

    Instance variable: a variable defined in a class for which each object (instance) has a separate copy.

  • The word public means that there is no restriction on their use
  • To make use of instance variables, we must first instantiate an object:
    Phone iphone = new Phone();
    
  • The new operator allocates memory space for each instance variable
  • After instantiating an object, we can assign values to the variables:
    iphone.brand = "iPhone";
    iphone.model = "7S";
    iphone.price = 521.56;
  • Each object has its own copy of instance variables:
    Phone samsung = new Phone();
    samsung.brand = "Samsung";
    samsung.model = "Galaxy S8";
    samsung.price = 499.99;
    
  • Thus we can assign different values to the variables in different objects
  • Together, the iphone and samsung objects have six instance variables


Instance Methods

Method -- a named block of code defined inside a class.

  • In other languages, a method is known as a function, procedure or subroutine
  • Our Phone class has only one method definition:
    public void makeCall() {
         System.out.println(brand + " is now making a call.");
    }
    
  • All method definitions belong to some class and are defined in the class to which they belong
  • A method definition has two parts:
    • a heading: public void makeCall()
    • a body:
      {
          System.out.println(brand + " is now making a call.");
      }
      
  • You call a method you write the same way you call a method for a predefined class
  • When we call a method, we pass the flow of control to the method
  • In this case, the method executes the single statement:
    System.out.println(brand + " is now making a call.");
    
  • When the method finishes executing all its statements, the flow of control returns to the calling point
  • In this case, the caller was one of these lines in the main() method of PhoneTest:
    iphone.makeCall();
    samsung.makeCall();
    
  • Both of these method calls transferred control to the makeCall() method of the Phone class
  • Both times the method returned after executing the last command of the method

Review Summary

  • Java programs primarily consist of objects that interact with each other
  • An object is a person, place or thing that either performs some action in a situation or is acted upon
  • Software objects are often simplifications or real world objects
  • The process of simplifying real world objects without losing their essential features is known as abstraction
  • To describe a software object, we write code for both data and actions
  • We write all the code describing an object in a single software construct called a class
  • The class is like a blueprint and is the set of rules for creating an object
  • All Java code is written using classes
  • A class uses instance variables to store the data for an object
  • The actions that an object can perform are defined in methods
  • A method is a set of statements that performs a specific task
  • When you want the statements executed, you call the method


Activity 6.1: Writing a Class (10 pts)

  • Open up a new Java project called Activity6 and create a class called Person
  • Inside of the class, define three attributes that a person has as variables of the class
    • Name
    • Age
    • Gender
  • Next, define two actions that can be performed as methods of the class:
    • greeting:
      • The method is named greeting
      • It takes no parameters
      • It prints out the message "Hi, my name is " + name + "!"
      • It returns nothing
    • addYear:
      • The method is named addYear
      • It takes in no parameters
      • It adds one year to the person's age
      • It returns nothing
  • Then, create a new Java file called PersonTest.java.
  • Copy and paste the below test code into PersonTest.java:

/**
* @author
* CIS 36B, Activity 6.1
*/

public class PersonTest {
    public static void main(String[] args) {
        Person wen = new Person();
        wen.name = "Wen";
        wen.age = 19;
        wen.gender = "male";
        wen.greeting();
        wen.addYear();
        System.out.println("I just turned " + wen.age + " years old.");
    }
}

  • Now, run the program and verify that you get the following output:
Hi, my name is Wen!
I just turned 20 years old.
  • When you are getting the correct output, submit your Person.java file to Canvas.

2. Using Objects with Arrays and ArrayLists

  • In Java, we can store object types in an array or an ArrayList.
  • For example, what will the below code display to the console?

Person p1 = new Person();
p1.name = "Jessica";
p1.age = 25;
p1.gender = "female";

Person p2 = new Person();
p2.name = "Ping";
p2.age = 30;
p2.gender = "male";

Person p3 = new Person();
p3.name = "Abda";
p3.age = 45;
p3.gender = "female";

Person[] team = new Person[3];
team[0] = p1;
team[1] = p2;
team[2] = p3;

team[1].greeting(); //What will this display?
//Note that team[1] will be a Person object

  • Alternately, we could use an ArrayList to store the 3 Person objects.
  • What will the below code display to the console?
Person p1 = new Person();
p1.name = "Jessica";
p1.age = 25;
p1.gender = "female";

Person p2 = new Person();
p2.name = "Ping";
p2.age = 30;
p2.gender = "male";

Person p3 = new Person();
p3.name = "Abda";
p3.age = 45;
p3.gender = "female";

ArrayList<Person> team = new ArrayList<Person>();
team.add(p1);
team.add(p2);
team.add(p3);

Person temp = team.get(0);
temp.greeting(); //What will this display?
//Alternately: team.get(0).greeting();


3. More About Methods


Overloading Methods

  • You can have several methods with the same name in a class
  • However, each method must have a different parameter list for each method:
    • Number of parameters
    • Parameter types
    • Order of parameters
  • For example we could have all of these methods in a class
public static void printArray(String[] s) {
    for (int i = 0; i < s.length; i++) {
        System.out.print(s[i] + ", ");
    }
}


public static void printArray(String[] s, int currSize) {
    for (int i = 0; i < currSize; i++) {
        System.out.print(s[i] + ", ");
    }
}


public static void printArray(double[] s) {
    for (int i = 0; i < s.length; i++) {
        System.out.print(s[i] + ", ");
    }
}

  • The method name and parameter list together are known as the method signature
  • Note that the return type is not part of the signature
  • The compiler cannot distinguish between two methods with the same signature but different return types
  • The following example demonstrates method overloading

Example Demonstrating Method Overloading

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

public class Phone {

    public String brand;
    public String model;
    public double price;

    public void makeCall() { System.out.println(brand + " is now making a call."); }


    public void makeCall(String name) {
        System.out.println(brand + " is now making a call to " + name);
    }
}

Okay to do - Type of Parameter(s) Must Differ

public double area (double radius) {
return radius * radius * 3.14;
}
public int area (int length, int width) {
return length * width;
}
public double area (double base, double height) {
return 0.5 * base * height;
}
Not okay to do - Return Type is Not Enough to Differentiate
public double area (int radius) {
    return radius * radius * 3.14;
}

public int area (int side) {
    return side * side;
}

Not okay to do - Parameter Names Not Enough to Differentiate

public double area (int radius) {
    return radius * radius * 3.14;
}

public double area (int side) {
    return side * side * .5;
}



Activity 6.2: Person Class with Method Overloading and ArrayLists (10 pts)

  • Open up your Person class from the last activity.
  • Add a second method to this class. Here are the specifications for this method:
    • The method is named greeting
    • It takes in one String parameter for another person's name
    • It prints out the message "Hi, " + otherName + "!"
    • It returns nothing.
  • Add a final method to this class.
    • The method is named printPerson
    • It prints a Person's name, age and gender to the console, in the format
Name: <name>
Age: <age>
Gender: <gender>
  • It returns nothing
  • Copy and paste the new test file below into PersonTest.java (you can erase the old contents of the file)
    • Add the missing 4 lines of code.
    • Then run your code to verify you have the correct output (shown below):

/**
 * @author
 * CIS 36B, Activity 6.2
 */
import java.util.Scanner;
import java.util.ArrayList;

public class PersonTest {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Person wen = new Person();
        wen.name = "Wen";
        wen.age = 19;
        wen.gender = "male";
        wen.greeting();
      
        System.out.print("\nWhat's your name: ");
        String name = input.nextLine();
        //call greeting method passing in name parameter
       
        System.out.print("\nHow old are you: ");
        int age = input.nextInt();
        System.out.print("What is your gender: ");
        String gender = input.next();
       
        //make a new Person here and assign that Person the name, age and gender read from console   
       
       
        ArrayList<Person> pair = new ArrayList<Person>(2);
        pair.add(wen);
        //add second person to ArrayList here
       
        System.out.println("\nPair Programming Partners: ");
        for (int i = 0; i < pair.size(); i++) {
            //add a line of code to call printPerson on each person in ArrayList
        }
       
    }
}

  • Now, run the program and verify that you get the new output (given the below input):
Hi, my name is Wen!

What's your name: Maria
Hi, Maria!

How old are you: 20
What is your gender: female

Pair Programming Partners:
Name: Wen
Age: 19
Gender: male

Name: Maria
Age: 20
Gender: female

  • When you are getting the correct output, submit your Person.java *and* PersonTest.java file to Canvas.


Wrap Up: 

  • Answer the Practice Exam Questions on Canvas for this lesson


Upcoming Assignments:

  • Activities 6.1 and 6.2 due Thursday at 11:59pm
  • Lesson 6 Practice Exam Questions due Thursday at 11:59pm
  • Quiz 3 due Friday at 11:59pm
  • Peer Review of Lesson 5 and 6 Practice Exam Questions due Saturday at 11:59pm
  • Lab 3 due Monday at 11:59pm

~ Have a Good Weekend! ~