Object-Oriented Programming in Java Buzzwords

responsibility-driven design inheritance encapsulation iterators overriding coupling cohesion javadoc interface collection classes mutator methods

polymorphic method calls

CS2336: Object-Oriented Programming in Java 2 What to Expect

• Expect: fundamental concepts, principles, and techniques of object- oriented programming • Not to expect: language details, all Java APIs, JSP/JavaServlet, use of specific tools

CS2336: Object-Oriented Programming in Java 3 Fundamental concepts

• object • class • method • parameter •

CS2336: Object-Oriented Programming in Java 4 What is OOP?

• OOP: – identifying objects and having them collaborate with each other • procedural programming: – identifying steps that need to be taken to perform a task

CS2336: Object-Oriented Programming in Java 5 Objects and classes

• objects – represent ‘things’ from the real world, or from some problem domain (example: “the red car down there in the car park”) – An object has a unique identity, state, and behaviors • classes – represent all objects of a kind (example: “car”)

CS2336: Object-Oriented Programming in Java 6 Methods and parameters

• Objects have operations which can be invoked (Java calls them methods). • The behavior of an object is defined by a set of methods. • Methods may have parameters to pass additional information needed to execute. • Methods may return a result via a return value. • Method signature specifies the types of the parameters and return values

CS2336: Object-Oriented Programming in Java 7 Data Types

• Parameters have data types, which specify what kind of data should be passed to a parameter. • There are two general kinds of types: primitive types, where values are stored in variables directly, and object types, where references to objects are stored in variables.

CS2336: Object-Oriented Programming in Java 8 Other observations

• An object has attributes: values stored in data fields. • The state of an object consists of a set of data fields with their current values.

CS2336: Object-Oriented Programming in Java 9 Other observations • Many instances can be created from a single class. • The class defines what fields an object has, but each object stores its own set of values (the state of the object). • The class provides a special type of methods, known as constructors, which are invoked to construct objects from the class

CS2336: Object-Oriented Programming in Java 10 Classes class Circle { /** The radius of this circle */ double radius = 0.0; Data field

/** Construct a circle object */ Circle() { } Constructors /** Construct a circle object */ Circle(double newRadius) { radius = newRadius; }

/** Return the area of this circle */ double getArea() { Method return radius * radius * 3.14159; } }

CS2336: Object-Oriented Programming in Java 11 Objects

Class Name: Circle A class template

Data Fields: radius is ______

Methods: getArea

Circle Object 1 Circle Object 2 Circle Object 3 Three objects of the Circle class Data Fields: Data Fields: Data Fields: radius is 10 radius is 25 radius is 125

CS2336: Object-Oriented Programming in Java 12 UML Class Diagram

UML Class Diagram Circle Class name

radius: double Data fields

Circle() Constructors and Circle(newRadius: double) methods

getArea(): double

UML notation circle1: Circle circle2: Circle circle3: Circle for objects radius = 1.0 radius = 25 radius = 125

CS2336: Object-Oriented Programming in Java 13 Constructors

Constructors are a special kind of Circle() { methods that are invoked to construct objects. }

Circle(double newRadius) { radius = newRadius; }

CS2336: Object-Oriented Programming in Java 14 Constructors, cont. • A constructor with no parameters is referred to as a no-arg constructor. • Constructors must have the same name as the class itself. • Constructors do not have a return type— not even void. • Constructors are invoked using the new operator when an object is created. • Constructors play the role of initializing objects. CS2336: Object-Oriented Programming in Java 15 Creating Objects Using Constructors

new ClassName();

Example: new Circle();

new Circle(5.0);

CS2336: Object-Oriented Programming in Java 16 Default Constructor A class may be declared without constructors. • A no-arg constructor with an empty body is implicitly declared in the class. (a default constructor) • This constructor is provided automatically only if no constructors are explicitly declared in the class.

CS2336: Object-Oriented Programming in Java 17 Example: Ticket machines–an external view • Exploring the behavior of a typical ticket machine. – Use the naive-ticket-machine project. – Machines supply tickets of a fixed price. – Methods insertMoney, getBalance, and printTicket are used to enter money, keep track of balance, and print out tickets.

CS2336: Object-Oriented Programming in Java 18 Ticket machines – an internal view • Interacting with an object gives us clues about its behavior. • Looking inside allows us to determine how that behavior is provided or implemented. • All Java classes have a similar-looking internal view.

CS2336: Object-Oriented Programming in Java 19 Basic class structure

The outer wrapper of public class TicketMachine { TicketMachine Inner part of the class omitted. }

public class ClassName { Fields The contents of a Constructors Methods class }

CS2336: Object-Oriented Programming in Java 20 Fields

• Fields store values public class TicketMachine for an object. { private int price; • They are also known private int balance; as instance variables. private int total;

• Fields define the Further details omitted. } state of an object.

type visibility modifier variable name

private int price;

CS2336: Object-Oriented Programming in Java 21 Constructors

• Constructors public TicketMachine(int ticketCost) initialize an object. { price = ticketCost; • They have the same balance = 0; name as their class. total = 0; } • They store initial values into the fields. • They often receive external parameter values for this.

CS2336: Object-Oriented Programming in Java 22 Assignment

• Values are stored into fields (and other variables) via assignment statements: – variable = expression; – price = ticketCost; • A variable stores a single value, so any previous value is lost.

CS2336: Object-Oriented Programming in Java 23 Accessor methods

• Methods implement the behavior of objects. • Accessors provide information about an object. • Methods have a structure consisting of a header and a body. • The header defines the method’s signature. public int getPrice() • The body encloses the method’s statements.

CS2336: Object-Oriented Programming in Java 24 Accessor methods

return type visibility modifier method name parameter list public int getPrice() (empty) { return price; return statement } start and end of method body (block)

CS2336: Object-Oriented Programming in Java 25 Test public class CokeMachine { private price; • What is public CokeMachine() wrong { here? price = 300 } (there are five public int getPrice errors!) { return Price; }

CS2336: Object-Oriented Programming in Java 26 Test public class CokeMachine { int private price; • What is public CokeMachine() wrong { here? price = 300; } (there are five public int getPrice() errors!) { return- Price; } } CS2336: Object-Oriented Programming in Java 27 Mutator methods

• Have a similar method structure: header and body. • Used to mutate (i.e., change) an object’s state. • Achieved through changing the value of one or more fields. – Typically contain assignment statements. – Typically receive parameters.

CS2336: Object-Oriented Programming in Java 28 Mutator methods

visibility modifier return type method name parameter

public void insertMoney(int amount) { balance = balance + amount; } field being mutated assignment statement

CS2336: Object-Oriented Programming in Java 29 Printing from methods

public void printTicket() { // Simulate the printing of a ticket. System.out.println("##################"); System.out.println("# Ticket"); System.out.println("# " + price + " cents."); System.out.println("##################"); System.out.println();

// Update the total collected with the balance. total = total + balance; // Clear the balance. balance = 0; }

CS2336: Object-Oriented Programming in Java 30 Quiz-String concatenation

• System.out.println(5 + 6 + "hello"); 11hello!

• System.out.println("hello" + 5 + 6); hello56!

CS2336: Object-Oriented Programming in Java 31 Local variables

• Fields are one sort of variable. – They store values through the life of an object. – They are accessible throughout the class. • Methods can include shorter-lived variables. – They exist only as long as the method is being executed. – They are only accessible from within the method.

CS2336: Object-Oriented Programming in Java 32 and life time

• The scope of a local variable is the block it is declared in. • The lifetime of a local variable is the time of execution of the block it is declared in.

CS2336: Object-Oriented Programming in Java 33 Local variables

A local variable public int refundBalance() { int amountToRefund; amountToRefund = balance; balance = 0; return amountToRefund; }

CS2336: Object-Oriented Programming in Java 34 Declaring Object Reference Variables To reference an object, assign the object to a reference variable. To declare a reference variable, use the syntax: ClassName objectRefVar;

Example: Circle myCircle;

CS2336: Object-Oriented Programming in Java 35 Declaring/Creating Objects in a Single Step ClassName objectRefVar = new ClassName();

Assign object reference Create an object Example: Circle myCircle = new Circle();

CS2336: Object-Oriented Programming in Java 36 Accessing Objects

• Referencing the object’s data: objectRefVar.data e.g., myCircle.radius

• Invoking the object’s method:

objectRefVar.methodName(arguments) e.g., myCircle.getArea()

CS2336: Object-Oriented Programming in Java 37 animation Trace Code

Declare myCircle Circle myCircle = new Circle(5.0);

SCircle yourCircle = new Circle(); myCircle no value yourCircle.radius = 100;

CS2336: Object-Oriented Programming in Java 38 animation Trace Code, cont.

Circle myCircle = new Circle(5.0);

Circle yourCircle = new Circle(); myCircle no value

yourCircle.radius = 100; : Circle

radius: 5.0

Create a circle

CS2336: Object-Oriented Programming in Java 39 animation Trace Code, cont.

Circle myCircle = new Circle(5.0);

Circle yourCircle = new Circle(); myCircle reference value yourCircle.radius = 100;

Assign object : Circle reference to myCircle radius: 5.0

CS2336: Object-Oriented Programming in Java 40 animation Trace Code, cont.

Circle myCircle = new Circle(5.0); myCircle reference value

Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

yourCircle no value

Declare yourCircle

CS2336: Object-Oriented Programming in Java 41 animation Trace Code, cont.

Circle myCircle = new Circle(5.0); myCircle reference value

Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

yourCircle no value

: Circle

Create a new radius: 0.0 Circle object

CS2336: Object-Oriented Programming in Java 42 animation Trace Code, cont.

Circle myCircle = new Circle(5.0); myCircle reference value

Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

yourCircle reference value

Assign object reference to : Circle yourCircle radius: 0.0

CS2336: Object-Oriented Programming in Java 43 animation Trace Code, cont.

Circle myCircle = new Circle(5.0); myCircle reference value

Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

yourCircle reference value

: Circle

Change radius in radius: 100.0 yourCircle

CS2336: Object-Oriented Programming in Java 44 Caution- non- methods

• Circle.getArea() (WRONG)

• objectRefVar.methodName(arguments) (e.g., myCircle.getArea()).

• More explanations will be given in the section on “Static Variables, Constants, and Methods.”

CS2336: Object-Oriented Programming in Java 45 Reference Data Fields

public class Student { String name; // name has default value null int age; // age has default value 0 boolean isScienceMajor; // isScienceMajor has default value false char gender; // has default value '\u0000' }

CS2336: Object-Oriented Programming in Java 46 Example

• Java assigns no default value to a local variable inside a method.

public class Test { public static void main(String[] args) { int x; // x has no default value String y; // y has no default value System.out.println("x is " + x); System.out.println("y is " + y); } } Compilation error: variables not initialized

CS2336: Object-Oriented Programming in Java 47 Differences between Variables of Primitive Data Types and Object Types

Created using new Circle() Primitive type int i = 1 i 1

Object type Circle c c reference c: Circle

radius = 1

CS2336: Object-Oriented Programming in Java 48 Copying Variables of Primitive Data Types and Object Types

Primitive type assignment i = j

Before: After:

i 1 i 2

j 2 j 2 Object type assignment c1 = c2

Before: After:

c1 c1

c2 c2

c1: Circle C2: Circle c1: Circle C2: Circle radius = 5 radius = 9 radius = 5 radius = 9

CS2336: Object-Oriented Programming in Java 49 Garbage Collection

The object previously referenced by c1 is no longer referenced. This object is known as garbage. Garbage is automatically collected by JVM.

CS2336: Object-Oriented Programming in Java 50 Static Variables, Constants, and Methods • Static variables are shared by all the instances of the class. • Static methods are not tied to a specific object. • Static constants are final variables shared by all the instances of the class. • To declare static variables, constants, and methods, use the static modifier.

CS2336: Object-Oriented Programming in Java 51 Example

instantiate circle1 Memory

radius = 1 1 radius After two Circle Circle numberOfObjects = 2 objects were created, numberOfObjects radius: double is 2. numberOfObjects: int 2 numberOfObjects getNumberOfObjects(): int +getArea(): double instantiate circle2

radius = 5 5 radius UML Notation: numberOfObjects = 2 +: public variables or methods underline: static variables or methods

CS2336: Object-Oriented Programming in Java 52 Visibility Modifiers By default, the class, variable, or method can be accessed by any class in the same package.

• Public: The class, data, or method is visible to any class in any package.

• Private: The data or methods can be accessed only by the declaring class.

The get and set methods are used to read and modify private properties.

CS2336: Object-Oriented Programming in Java 53 package p1; package p2; public class C1 { public class C2 { public class C3 { public int x; void aMethod() { void aMethod() { int y; C1 o = new C1(); C1 o = new C1(); private int z; can access o.x; can access o.x; can access o.y; cannot access o.y; public void m1() { cannot access o.z; cannot access o.z; } void m2() { can invoke o.m1(); can invoke o.m1(); } can invoke o.m2(); cannot invoke o.m2(); private void m3() { cannot invoke o.m3(); cannot invoke o.m3(); } } } } } }

package p1; package p2; class C1 { public class C2 { public class C3 { ... can access C1 cannot access C1; } } can access C2; } The private modifier restricts access to within a class, the default modifier restricts access to within a package, and the public modifier enables unrestricted access.

CS2336: Object-Oriented Programming in Java 54 Note • An object cannot access its private members, as shown in (b). • It is OK, however, if the object is declare in its own class, as shown in (a).

public class Foo { public class Test { private boolean x; public static void main(String[] args) { Foo foo = new Foo(); public static void main(String[] args) { System.out.println(foo.x); Foo foo = new Foo(); System.out.println(foo.convert()); System.out.println(foo.x); } System.out.println(foo.convert()); } }

private int convert() { return x ? 1 : -1; } } (b) This is wrong because x and convert are private in Foo. (a) This is OK because object foo is used inside the Foo class

CS2336: Object-Oriented Programming in Java 55 Introducing Arrays

• Array is a data structure that represents a collection of the same types of data.

CS2336: Object-Oriented Programming in Java 56 Declaring Array Variables • datatype[] arrayRefVar; Example: double[] myList;

Example: double myList[]; (not preferred)

CS2336: Object-Oriented Programming in Java 57 Creating Arrays arrayRefVar = new datatype[arraySize]; Example: myList = new double[10];

CS2336: Object-Oriented Programming in Java 58 Declaring and Creating in One Step double[] myList = new double[4]; myList[0] references the first element in the array. myList[3] references the last element in the array. the indices are from 0 to 3 myList.Length …….. return 4

CS2336: Object-Oriented Programming in Java 59 Declaring, creating, initializing Using the Shorthand Notation double[] myList = {1.9, 2.9, 3.4, 3.5}; is equivalent to double[] myList = new double[4]; myList[0] = 1.9; myList[1] = 2.9; myList[2] = 3.4; myList[3] = 3.5;

CS2336: Object-Oriented Programming in Java 60 Default Values

When an array is created, its elements are assigned the default value of

0 for the numeric primitive data types, '\u0000' for char types, and false for boolean types.

CS2336: Object-Oriented Programming in Java 61 animation Trace Program with Arrays

Declare array variable values, create an array, and assign its reference to values

public class Test { public static void main(String[] args) { After the array is created int[] values = new int[5]; 0 0

for (int i = 1; i < 5; i++) { 1 0

values[i] = i + values[i-1]; 2 0 } 3 0 values[0] = values[1] + values[4]; 4 0 } }

CS2336: Object-Oriented Programming in Java 62 animation Trace Program with Arrays

i becomes 1

public class Test { public static void main(String[] args) { After the array is created int[] values = new int[5]; for (int i = 1; i < 5; i++) { 0 0

values[i] = i + values[i-1]; 1 0 } 2 0 values[0] = values[1] + values[4]; 3 0 4 0 } }

CS2336: Object-Oriented Programming in Java 63 animation Trace Program with Arrays

i (=1) is less than 5

public class Test { public static void main(String[] args) { int[] values = new int[5]; After the array is created

for (int i = 1; i < 5; i++) { 0 0

values[i] = i + values[i-1]; 1 0 } 2 0 values[0] = values[1] + values[4]; 3 0 } 4 0 }

CS2336: Object-Oriented Programming in Java 64 animation Trace Program with Arrays

After this line is executed, value[1] is 1

public class Test { public static void main(String[] args) { After the first iteration int[] values = new int[5]; 0 0

for (int i = 1; i < 5; i++) { 1 1 values[i] = i + values[i-1]; 2 0 } 3 0 values[0] = values[1] + values[4]; 4 0 } }

CS2336: Object-Oriented Programming in Java 65 animation Trace Program with Arrays

After i++, i becomes 2

public class Test { public static void main(String[] args) {

int[] values = new int[5]; After the first iteration for (int i = 1; i < 5; i++) { 0 0

values[i] = i + values[i-1]; 1 1 } 2 0 values[0] = values[1] + values[4]; 3 0 4 0 } }

66 animation Trace Program with Arrays

i (= 2) is less than 5 public class Test { public static void main(String[] args) { int[] values = new int[5]; After the first iteration for (int i = 1; i < 5; i++) { 0 0

values[i] = i + values[i-1]; 1 1 } 2 0 values[0] = values[1] + 3 0 values[4]; 4 0 } }

67 animation Trace Program with Arrays

After this line is executed, values[2] is 3 (2 + 1)

public class Test { public static void main(String[] args) { After the second iteration int[] values = new int[5]; 0 0

for (int i = 1; i < 5; i++) { 1 1 values[i] = i + values[i-1]; 2 3 } 3 0 values[0] = values[1] + values[4]; 4 0 } }

CS2336: Object-Oriented Programming in Java 68 animation Trace Program with Arrays

After this, i becomes 3.

public class Test { public static void main(String[] args) { After the second iteration int[] values = new int[5]; 0 0

for (int i = 1; i < 5; i++) { 1 1 values[i] = i + values[i-1]; 2 3 } 3 0 values[0] = values[1] + values[4]; 4 0 } }

CS2336: Object-Oriented Programming in Java 69 animation Trace Program with Arrays

i (=3) is still less than 5.

public class Test { public static void main(String[] args) { After the second iteration int[] values = new int[5]; 0 0

for (int i = 1; i < 5; i++) { 1 1 values[i] = i + values[i-1]; 2 3 } 3 0 values[0] = values[1] + values[4]; 4 0 } }

CS2336: Object-Oriented Programming in Java 70 animation Trace Program with Arrays

After this line, values[3] becomes 6 (3 + 3)

public class Test { public static void main(String[] args) { After the third iteration int[] values = new int[5]; 0 0

for (int i = 1; i < 5; i++) { 1 1 values[i] = i + values[i-1]; 2 3 } 3 6 values[0] = values[1] + values[4]; 4 0 } }

CS2336: Object-Oriented Programming in Java 71 animation Trace Program with Arrays

After this, i becomes 4

public class Test { public static void main(String[] args) { After the third iteration int[] values = new int[5]; 0 0

for (int i = 1; i < 5; i++) { 1 1 values[i] = i + values[i-1]; 2 3 } 3 6 values[0] = values[1] + values[4]; 4 0 } }

CS2336: Object-Oriented Programming in Java 72 animation Trace Program with Arrays

i (=4) is still less than 5

public class Test { public static void main(String[] args) { After the third iteration int[] values = new int[5]; 0 0

for (int i = 1; i < 5; i++) { 1 1 values[i] = i + values[i-1]; 2 3 } 3 6 values[0] = values[1] + values[4]; 4 0 } }

CS2336: Object-Oriented Programming in Java 73 animation Trace Program with Arrays

After this, values[4] becomes 10 (4 + 6)

public class Test { public static void main(String[] args) { After the fourth iteration int[] values = new int[5]; 0 0

for (int i = 1; i < 5; i++) { 1 1 values[i] = i + values[i-1]; 2 3 } 3 6 values[0] = values[1] + values[4]; 4 10 } }

CS2336: Object-Oriented Programming in Java 74 animation Trace Program with Arrays

After i++, i becomes 5

public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; After the fourth iteration }

values[0] = values[1] + values[4]; 0 0

} 1 1

} 2 3

3 6

4 10

75 animation Trace Program with Arrays i ( =5) < 5 is false. Exit the loop

public class Test { public static void main(String[] args) { int[] values = new int[5];

for (int i = 1; i < 5; i++) { After the fourth iteration values[i] = i + values[i-1]; 0 0 } 1 1

values[0] = values[1] + values[4]; 2 3 } 3 6 } 4 10

76 animation Trace Program with Arrays

After this line, values[0] is 11 (1 + 10)

public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { 0 11

values[i] = i + values[i-1]; 1 1 } 2 3 values[0] = values[1] + values[4]; 3 6 } 4 10 }

CS2336: Object-Oriented Programming in Java 77 Array of Objects

Circle[] circleArray = new Circle[10];

circleArray reference circleArray[0] Circle object 0 circleArray[1]

… Circle object 1

circleArray[9] Circle object 9

CS2336: Object-Oriented Programming in Java 78 Immutable Objects and Classes • If the contents of an object cannot be changed once the object is created, the object is called an and its class is called an immutable class. • A class with all private data fields and without mutators is not necessarily immutable. For example, the following class Student has all private data fields and no mutators, but it is mutable.

CS2336: Object-Oriented Programming in Java 79 Example public class BirthDate { private int year; public class Student { private int month; private int id; private BirthDate birthDate; private int day;

public Student(int ssn, public BirthDate(int newYear, int year, int month, int day) { int newMonth, int newDay) { id = ssn; birthDate = new BirthDate(year, month, day); year = newYear; } month = newMonth; day = newDay; public int getId() { } return id; } public void setYear(int newYear) { public BirthDate getBirthDate() { year = newYear; return birthDate; } } } }

public class Test { public static void main(String[] args) { Student student = new Student(111223333, 1970, 5, 3); BirthDate date = student.getBirthDate(); date.setYear(2010); // Now the student birth year is changed! } }

CS2336: Object-Oriented Programming in Java 80 What Class is Immutable?

• must mark all data fields private and • no mutator methods and no accessor methods that would return a reference to a mutable data field object.

CS2336: Object-Oriented Programming in Java 81 Acknowledgement

The original authors of these slides are the authors of the textbook. The instructor made necessary modifications, with permissions from the authors.

CS2336: Object-Oriented Programming in Java 82