1 / 39

Chapter 8: Designing Classes

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 ). Accessor and Mutator Methods.

inoke
Download Presentation

Chapter 8: Designing Classes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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)

  2. 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.

  3. 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

  4. 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

  5. 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?)

  6. BankAccount class public void transfer(double amount, BankAccount otherAccount) { balance -= amount; otherAccount.balance += amount) }

  7. BankAccount class public void transfer(double amount, BankAccount otherAccount) { balance -= amount; otherAccount.balance += amount) } This method alters the explicit parameter, otherBalance.

  8. 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.

  9. Primitive parameters Consider the method: public static void change(int x, int y) { x = 123; y = 456; } And the following code segment int 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?

  10. 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 b int 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

  11. 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 b int 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 What is in a,b,x, and y after change method is executed? 10 11

  12. Constructor: Point Methods: setPoint toString Point class public class Point { Point(int x1, int y1) { x = x1; y = y1; } // two accessor methods here public void setPoint(intxCoordinate, intyCoordinate) { x = xCoordinate; y = yCoordinate; } public String toString() { String s="(" + x + "," + y + ")"; return s; } privateint x; privateint y; }

  13. Values of p1,p2, first and second BEFOREchangePoints method is executed? Point classTrying to replace references Consider the method public static void changePoints(Point first, Point second) { Point anotherPoint = new Point(1,1); first second first = anotherPoint; second = first; } Trying to change object references p2 Point p1 = new Point(1,2); p1 Point 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

  14. Values of p1,p2, first and second AFTERchangePoints method is executed? Point classTrying to replace references Consider the method public static void changePoints(Point first, Point second) { Point anotherPoint = new Point(1,1); first second first = anotherPoint; second = first; } anotherPoint Trying to change object references p2 Point p1 = new Point(1,2); p1 Point 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 = 1 x =1 y = 2 x = 3 y = 4

  15. Values of p1,p2, first and second BEFOREchangeState method is executed? 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

  16. Values of p1,p2, first and second AFTERchangeState method is executed? 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 Notice the values of x and y for p1 have changed state.

  17. Constructor: Student Methods: getGPA setGPA Student class public 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; }

  18. Two methods: change1 change2 What do they do? 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 executed Student 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?

  19. 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 executed Student 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

  20. 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.

  21. 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.

  22. 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);

  23. 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()NOTobj.methodName().

  24. FunNumber class public intcountDigits() { intnum = original; // original from constructor int digs = 0; while(num > 0) { num = (num/10); digs++; } return digs; } Call: intaNumber =// some integer input by user FunNumber 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.

  25. 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.

  26. 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).

  27. Static Fields (class fields)- belong to the class- Objects of the class share the static fields Every time a car is made, the counter numCarsMade is incremented. public class Car { public Car() { //private instance variables initialized here numCarsMade++; // number of cars manufactured so far } // Other public methods here. public static intgetCarsMade() { return numCarsMade; } // private instance fields here private static intnumCarsMade; // Counts cars instantiated }

  28. 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 intgetCarsMade() { return numCarsMade; } // private instance fields here private static intnumCarsMade=0; // Counts cars instantiated }

  29. 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 intnumCarsMade = 0; • This is executed once when the class is loaded. • Do nothing and the static field will be initialized with default values......which are????

  30. 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

  31. 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.

  32. Scope of variables • Parameter variables • Parameters variables are accessible within the method that they were passed.

  33. 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 } }

  34. 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.

  35. 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.

  36. 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.

  37. 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.

  38. 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.

  39. Problem: Which variables are accessible at each scopeCheck? public class Mystery { public void foo(intsomeValue) { 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 }

More Related