39
Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and Post conditions (8.5) Static Methods (8.6) Static Fields (8.7) Scope (8.8)

Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Embed Size (px)

Citation preview

Page 1: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Chapter 8: Designing Classes

Accessors, Mutators, and Immutable Classes(8.3)Side Effects(8.4)Parameter Passing (Advanced Topic 8.1)Preconditions and Post conditions (8.5)Static Methods (8.6)Static Fields (8.7)Scope (8.8)

Page 2: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Accessor and Mutator Methods

An accessor method does not change the state of its implicit parameter. getBalance method of BankAccount getNumerator method of Rational

A mutator (modifier) method can change the state of its implicit parameter. deposit method of BankAccount changes balance.

Page 3: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Immutable class

An immutable class has no mutator methods. The String class

Which of the following classes (if any) is immutable. Why (or why not)? Rational BankAccount String

Page 4: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Immutable class

An immutable class has no mutator methods. The String class

Which of the following classes (if any) is immutable. Why (or why not)? Rational no—reduce alters state BankAccount no—deposit alters state String OK

Page 5: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Side Effects

A side effect of a method is an observable behavior outside the object. System.out.print statements !!!

Minimize side effects.(Can we eliminate them?)

Page 6: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

BankAccount class

public void transfer(double amount, BankAccount otherAccount)

{balance -= amount;otherAccount.balance += amount)

}

Page 7: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

BankAccount class

public void transfer(double amount, BankAccount otherAccount)

{balance -= amount;otherAccount.balance += amount)

}

This method alters the explicit parameter, otherBalance.

Page 8: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Parameters

A method can never change parameters of primitive type.

A method can change the state of an object reference but it cannot replace the reference with another.

Page 9: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Primitive parameters

Consider the method:public static void change(int x, int y){

x = 123;y = 456;

}

And the following code segmentint a = 10;int b = 11;System.out.println("Before change:");System.out.println("a = " + a + " b = " + b)

change(a,b);System.out.println("After change:");System.out.println("a = " + a + " b = " + b);

What is in a,b,x, and y before change method is executed?

Page 10: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Primitive parameters

Consider the method:public static void change(int x, int y) x y{

x = 123;y = 456;

}

And the following code segment a bint a = 10;int b = 11;System.out.println("Before change:");System.out.println("a = " + a + " b = " + b)

change(a,b);System.out.println("After change:");System.out.println("a = " + a + " b = " + b);

10 11

10 11

Page 11: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Trying to change primitive parameters

Consider the method:public static void change(int x, int y) x y{

x = 123;y = 456;

}

And the following code segment a bint a = 10;int b = 11;System.out.println("Before change:");System.out.println("a = " + a + " b = " + b)

a = 10 b = 11 change(a,b);

System.out.println("After change:");System.out.println("a = " + a + " b = " + b);

a = 10 b = 11

123 456

10 11

What is in a,b,x, and y after change method is executed?

Page 12: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Point classpublic class Point{ Point(int x1, int y1) {

x = x1; y = y1;

}// two accessor methods here

public void setPoint(int xCoordinate, int yCoordinate) { x = xCoordinate; y = yCoordinate; }

public String toString() {

String s="(" + x + "," + y + ")"; return s; } private int x; private int y;}

Constructor: Point

Methods: setPoint toString

Page 13: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Point classTrying to replace referencesConsider the methodpublic static void changePoints(Point first, Point second){

Point anotherPoint = new Point(1,1); first secondfirst = anotherPoint; second = first;

}

Trying to change object references p2Point p1 = new Point(1,2); p1Point p2 = new Point(3,4); System.out.println("Before call to changePoints:");System.out.println("p1 = " + p1);

System.out.println("p2 = " + p2); changePoints (p1,p2);

System.out.println("After call to changePoints:");System.out.println("p1 = " + p1);

System.out.println("p2 = " + p2);

x =1

y = 2

x = 3

y = 4

Values of p1,p2, first and second BEFORE changePoints method is executed?

Page 14: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Point classTrying to replace referencesConsider the methodpublic static void changePoints(Point first, Point second){

Point anotherPoint = new Point(1,1); first secondfirst = anotherPoint; second = first;

} anotherPoint

Trying to change object references p2Point p1 = new Point(1,2); p1Point p2 = new Point(3,4); System.out.println("Before call to changePoints:");System.out.println("p1 = " + p1);

System.out.println("p2 = " + p2); changePoints (p1,p2);

System.out.println("After call to changePoints:");System.out.println("p1 = " + p1);

System.out.println("p2 = " + p2);

x =1

y = 2

x = 3

y = 4

x =1

y = 1

Values of p1,p2, first and second AFTER changePoints method is executed?

Page 15: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Point classChanging state

Consider the method public static void changeState(Point first, Point second) { first.setPoint(second.getX(),second.getY()); first second }

p1 p2 Point p1 = new Point(1,2);

Point p2 = new Point(3,4); System.out.println("Before call to changeState:");System.out.println("p1 = " + p1); System.out.println("p2 = " + p2);changeState (p1,p2);System.out.println("After call to changeState:"); System.out.println("p1 = " + p1); System.out.println("p2 = " + p2);

x =1

y = 2

x = 3

y = 4

Values of p1,p2, first and second BEFORE changeState method is executed?

Page 16: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Point classChanging state

Consider the method public static void changeState(Point first, Point second) { first.setPoint(second.getX(),second.getY()); first second }

p1 p2 Point p1 = new Point(1,2);

Point p2 = new Point(3,4); System.out.println("Before call to changeState:");System.out.println("p1 = " + p1); System.out.println("p2 = " + p2);changeState (p1,p2);System.out.println("After call to changeState:"); System.out.println("p1 = " + p1); System.out.println("p2 = " + p2);

x =3

y = 4

x = 3

y = 4

Values of p1,p2, first and second AFTER changeState method is executed?

Notice the values of x and y for p1 have changed state.

Page 17: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Student classpublic class Student{

public Student(String first, String last, String idNumber, double gradePointAvg)

{ // private instance field initialized;}public double getGPA(){

return gpa;}

public void setGPA(double newGPA){

gpa = newGPA;}private String fname;private String lname;private String id;private double gpa;

}

Constructor: Student

Methods: getGPA setGPA

Page 18: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Problem:

Consider a client program of the Student class that includes the following methods.public static void change1(Student stud1, Student stud2){

stud1 = stud2;}

public static void change2(Student stud1, Student stud2){

stud1.setGPA(stud2.getGPA());}

After the code segment below is executedStudent student1 = new Student("Kevin", "Brown", "333", 1.0);Student student2 = new Student("Joe", "Smith", "111", 2.57);Student student3 = new Student("Marie", "Jones", "222", 3.85);change1(student1,student2);change2(student3, student1);

What are the gpas of student1, student2, and student3?

Two methods: change1 change2What do they do?

Page 19: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Problem:

Consider a client program of the Student class that includes the following methods.public static void change1(Student stud1, Student stud2){

stud1 = stud2;}

public static void change2(Student stud1, Student stud2){

stud1.setGPA(stud2.getGPA());}

After the code segment below is executedStudent student1 = new Student("Kevin", "Brown", "333", 1.0);Student student2 = new Student("Joe", "Smith", "111", 2.57);Student student3 = new Student("Marie", "Jones", "222", 3.85);change1(student1,student2);change2(student3, student1);

What are the gpas of student1, student2, and student3?

Student1 = 1.0, student2 = 2.57, student3 = 1.0

Page 20: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Preconditions and Postconditions

Precondition A precondition is a requirement that the caller

of a method must meet. If a method is called with the precondition

being violated, the method is not responsible for computing the correct result.

It is the responsibility of the calling method to insure that the precondition is met.

Page 21: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Preconditions and Postconditions

Postcondition If the precondition of the method is satisfied,

the postcondition is a promise that the return value is computed correctly or that the object is in a certain state after the method call is completed.

If the precondition is not met, no promise is made.

Page 22: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Static Methods

A static method has no implicit paramter. Two ways:

Math.sqrt(4); // no object

public static void printInfo(Student s) { System.out.println(s.getName()); }

call: printInfo(aStudent);

Page 23: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Static Methods (aka class methods)

public static void main(String[] args) When the program starts there are no objects.

the first method in the program must be a static method.

Minimize the number of static methods. static method means class method.

belongs to a class NOT to an object. Class.methodName() NOT obj.methodName().

Page 24: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

FunNumber class

public int countDigits() { int num = original; // original from

constructorint digs = 0;

while(num > 0) { num = (num/10); digs++; } return digs; }

Call:int aNumber = // some integer input by userFunNumber n = new FunNumber(aNumber); System.out.println("Number of digits is: " + n.countDigits());

Notice the call statement identifies the object and the method and passes no parameter.

Page 25: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Uitlity FunNumber class

public static int countDigits(int aNumber) { int num = aNumber;

int digs = 0; while(num > 0) { num = (num/10); digs++; } return digs; }

Call:int n = // some integer input by user System.out.println("Number of digits is: " +

FunNumber.countDigits(n));

Notice the call statement identifies the Class name and the method and passes the n value as the parameter.

Page 26: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Static Fields

A static field belongs to a class not an object.

Consider a Car class used by a car manufacturer. It is important that the manufacturer keeps track of the number of cars manufactured (instantiated).

Page 27: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Static Fields (class fields)- belong to the class- Objects of the class share the static fields

public class Car{ public Car() { //private instance variables initialized here numCarsMade++; // number of cars manufactured so far } // Other public methods here. public static int getCarsMade() { return numCarsMade; } // private instance fields here private static int numCarsMade; // Counts cars instantiated }

Every time a car is made, the counter numCarsMade is incremented.

Page 28: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

How do we initialize static fields?

public class Car{ public Car() { //private instance variables initialized here numCarsMade++; // number of cars manufactured so far } // Other public methods here. public static int getCarsMade() { return numCarsMade; } // private instance fields here

private static int numCarsMade=0; // Counts cars instantiated

}

Page 29: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

How do we initialize static fields?

You can't initialize them in the constructor. Why not?

Two ways to initialize static fields: Use an explicit initializer:

private static int numCarsMade = 0; This is executed once when the class is loaded.

Do nothing and the static field will be initialized with default values......which are????

Page 30: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Scope of variables

The word scope is used to describe the parts of a program in which a variable is accessible. local variables parameter variables variables declared in loop initialization

Page 31: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Scope of variables

Local variables accessible from the point of its declaration to

the end of the block that encloses it. If a variable is declared in the loop

initialization, it is accessible within the loop. If a variable is declared at the start of a

method, it is accessible in that method.

Page 32: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Scope of variables

Parameter variables Parameters variables are accessible within

the method that they were passed.

Page 33: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Naming and scope of variables

Naming variables If you try to name two local variables with overlapping scopes

with the same name, the compiler will complain. public static void main(String[] args) {

System.out.println("Starting Chapter 9...");

int x = 5;for (int x = 0; x < 10; x++){ //do stuff

}}

Page 34: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Naming and scope of variables Naming variables

You can have local variables with the same name if their scopes do not overlap. public static void main(String[] args) {

System.out.println("Starting Chapter 9...");

for (int x = 0; x < 10; x++){ //do stuff

} for (int x = 10; x > 0; x--) { // do stuff }

}

To avoid all of this confusion, use different names for different variables.

Page 35: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Scope of Class Members

Within a method of a class, you can access all other methods and all fields by their simple names (without prefix of an object name).

If you are using a method outside the object, you must qualify it by prefixing the method name with the object name (for an instance method) or With the class name (for a class method– static method).

An instance method call without an implicit parameter indicates that the method is called on this.

Page 36: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Initialization of variables

Local variables: A local variable must be initialized before you use it. Failure to initialize will cause the compiler to complain.

Parameter variables are initialized with the values that are supplied by the calling method.

Page 37: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Initialization of variables

Instance Fields should be initialized in the constructor of the class. If instance fields are not initialized explicitly, default values are assigned. Numbers are initialized to 0. Objects to null. boolean are initialized to false.

Page 38: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Initialization of variables

Static fields are initialized when the class is loaded. This should be done by an explicit initializer. However, if no initialization is done explicitly,

default values are assigned. Static constants are initialized with a value.

Page 39: Chapter 8: Designing Classes Accessors, Mutators, and Immutable Classes(8.3) Side Effects(8.4) Parameter Passing (Advanced Topic 8.1) Preconditions and

Problem: Which variables are accessible at each scopeCheck?

public class Mystery{ public void foo(int someValue) {

doStuff(someValue); // scopeCheck1 }

public void doStuff(int number) {

int count=0;for(int r =1; r<=number; r++){ for (int c = 1; c <=r; c++) {

System.out.print("whatever");count++;//scopeCheck2

} System.out.println();}// scopeCheck3

}