Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 9 Objects and Classes

Similar presentations


Presentation on theme: "Chapter 9 Objects and Classes"— Presentation transcript:

1 Chapter 9 Objects and Classes

2 Motivations Learning the preceding chapters
you are capable of solving many programming problems using selections, loops, methods, and arrays. However, these Java features are not sufficient for developing graphical user interfaces and large scale software systems. Suppose you want to develop a graphical user interface as shown below. How do you program it?

3 Objectives To describe objects and classes, and use classes to model objects (§9.2). To use UML graphical notation to describe classes and objects (§9.2). To demonstrate how to define classes and create objects (§9.3). To create objects using constructors (§9.4). To access objects via object reference variables (§9.5). To define a reference variable using a reference type (§9.5.1). To access an object’s data and methods using the object member access operator (.) (§9.5.2). To define data fields of reference types and assign default values for an object’s data fields (§9.5.3). To distinguish between object reference variables and primitive data type variables (§9.5.4). To use the Java library classes Date, Random, and Point2D (§9.6). To distinguish between instance and static variables and methods (§9.7). To define private data fields with appropriate get and set methods (§9.8). To encapsulate data fields to make classes easy to maintain (§9.9). To develop methods with object arguments and differentiate between primitive-type arguments and object-type arguments (§9.10). To store and process objects in arrays (§9.11). To create immutable objects from immutable classes to protect the contents of objects (§9.12). To determine the scope of variables in the context of a class (§9.13). To use the keyword this to refer to the calling object itself (§9.14).

4 OO Programming Concepts
Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that can be distinctly identified. For example, a student, a desk, a circle, a button, and even a loan can all be viewed as objects.

5 OO Programming Concepts
An object has a unique identity, state, and behaviors. The state of an object consists of a set of data fields (also known as properties) with their current values. The behavior (also known as actions) of an object is defined by a set of methods.

6 OO Programming Concepts
In OO programming (e.g., Java), an object is associated with a memory space referenced by the object name. The memory space is allocated when using the new operator to create the object. The memory space holds the values of the data fields of the object.

7 Objects An object (an instance of a class ) has both a state and behavior. The state defines the object The behavior defines what the object does.

8 Classes Classes are constructs (templates) that define objects of the same type. A Java class uses variables to define data fields and methods to define behaviors. Constructors are special type of methods in the class Invoked to construct objects from the class. Multiple objects can be created from the same class.

9 Classes The programs we’ve written in previous examples have used classes defined in the Java standard class library. Now, we will begin to design programs that rely on classes that we write ourselves. The class that contains the main method is just the starting point of a program.

10 Classes

11 UML Class Diagram Unified Modeling Language

12 1  public class TestSimpleCircle {
2   /** Main method */ 3   public static void main(String[] args) { 4   // Create a circle with radius 1 5   SimpleCircle circle1 = new SimpleCircle(); 6   System.out.println("The area of the circle of radius " 7   + circle1.radius + " is " + circle1.getArea()); 8   9   // Create a circle with radius 25 10   SimpleCircle circle2 = new SimpleCircle(25); 11   System.out.println("The area of the circle of radius " 12   + circle2.radius + " is " + circle2.getArea()); 13   14   // Create a circle with radius 125 15   SimpleCircle circle3 = new SimpleCircle(125); 16   System.out.println("The area of the circle of radius " 17   + circle3.radius + " is " + circle3.getArea()); 18   19   // Modify circle radius 20   circle2.radius = 100; // or circle2.setRadius(100) 21   System.out.println("The area of the circle of radius " 22   + circle2.radius + " is " + circle2.getArea()); 23   } 24  }

13 Animation 26 // Define the circle class with two constructors
27  class SimpleCircle { 28   double radius; 29   30   /** Construct a circle with radius 1 */ 31   SimpleCircle() { 32   radius = 1; 33   } 34   35   /** Construct a circle with a specified radius */ 36   SimpleCircle(double newRadius) { 37   radius = newRadius; 38   } 39   40   /** Return the area of this circle */ 41   double getArea() { 42   return radius * radius * Math.PI; 43   } 44   45   /** Return the perimeter of this circle */ 46   double getPerimeter() { 47   return 2 * radius * Math.PI; 48   } 49   50   /** Set a new radius for this circle */ 51   void setRadius(double newRadius) { 52   radius = newRadius; 53   } 54  } Animation

14 Classes The two classes into one file
Only one class in the file can be a public class The public class must have the same name as the file name Each class in the source code is compiled into a .class file.

15 1  public class AlternativeCircle {
2   /** Main method */ 3   public static void main(String[] args) { 4   // Create a circle with radius 1 5   AlternativeCircle circle1 = new AlternativeCircle(); 6   System.out.println("The area of the circle of radius " 7   + circle1.radius + " is " + circle1.getArea()); 8   9   // Create a circle with radius 25 10   AlternativeCircle circle2 = new AlternativeCircle(25); 11   System.out.println("The area of the circle of radius " 12   + circle2.radius + " is " + circle2.getArea()); 13   14   // Create a circle with radius 125 15   AlternativeCircle circle3 = new AlternativeCircle(125); 16   System.out.println("The area of the circle of radius " 17   + circle3.radius + " is " + circle3.getArea()); 18   19   // Modify circle radius 20   circle2.radius = 100; 21   System.out.println("The area of the circle of radius " 22   + circle2.radius + " is " + circle2.getArea()); 23   }

16 25   double radius; 26   27   /** Construct a circle with radius 1 */ 28   AlternativeCircle() { 29   radius = 1; 30   } 31   32   /** Construct a circle with a specified radius */ 33   AlternativeCircle(double newRadius) { 34   radius = newRadius; 35   } 36   37   /** Return the area of this circle */ 38   double getArea() { 39   return radius * radius * Math.PI; 40   } 41   42   /** Return the perimeter of this circle */ 43   double getPerimeter() { 44   return 2 * radius * Math.PI; 45   } 46   47   /** Set a new radius for this circle */ 48   void setRadius(double newRadius) { 49   radius = newRadius; 50   } 51  }

17 Example: Defining Classes and Creating Objects
The + sign indicates a public modifier

18 Constructors Constructors are a special kind of methods that are invoked to construct objects. Circle() { } Circle(double newRadius) { radius = newRadius;

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

20 Creating Objects Using Constructors
new ClassName(); Example: new Circle(); new Circle(5.0);

21 Default Constructor A class may be defined without constructors.
In this case, a no-arg constructor with an empty body is implicitly defined in the class. This constructor, called a default constructor, is provided automatically only if no constructors are explicitly defined in the class.

22 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 myCircle1, myCircle2; //reference variables myCircle1 = new Circle(); //calls first constructor myCircle2 = new Circle(5.0); //calls second constructor

23 Declaring/Creating Objects in a Single Step
ClassName objectRefVar = new ClassName(); Example: Circle myCircle1 = new Circle(); Assign object reference Create an object Circle myCircle2 = new Circle(5.0);

24 Accessing Object’s Members
Referencing the object’s data: objectRefVar.data e.g., myCircle1.radius Invoking the object’s method: objectRefVar.methodName(arguments) e.g., myCircle1.getArea()

25 Trace Code animation Declare myCircle
Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle no value

26 Trace Code, cont. animation Circle myCircle = new Circle(5.0);
Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle no value Create a circle

27 Assign object reference to myCircle
animation Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value Assign object reference to myCircle

28 Trace Code, cont. Declare yourCircle animation
Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value yourCircle no value Declare yourCircle

29 Create a new Circle object
animation Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value yourCircle no value Create a new Circle object

30 Assign object reference to yourCircle
animation Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value yourCircle reference value Assign object reference to yourCircle

31 Change radius in yourCircle
animation Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value yourCircle reference value Change radius in yourCircle

32 Caution Recall that we used to invoke a method in the Math class.
Math.methodName(arguments) (e.g., Math.pow(3, 2.5)) to invoke a method in the Math class. Can you invoke getArea() using Circle1.getArea()? All the methods defined in the Math class are static (defined using the static keyword). However, method getArea() is non-static. It must be invoked from an object using this syntax: objectRefVar.methodName(arguments) (e.g., myCircle.getArea())

33 Reference Data Fields The data fields can be of reference types.
If a data field of a reference type does not reference any object, the data field holds a special literal value null (or null pointer) . For example, the following Student class contains a data field name of the String type. public class Student { // data fields String name; //default value null. Why? int age; //default value 0 boolean isScienceMajor; //default value false char gender; //default value '\u0000', prints out as 00 }

34 Default Value for a Data Field
If a data field of a reference type does not reference any object, the data field holds a special literal value, null. The default value of a data field is null for a reference type, 0 for a numeric type, false for a boolean type, and '\u0000' for a char type. However, Java assigns no default value to a local variable inside a method.

35 Default Value for a Data Field
public class Test { public static void main(String[] args) { Student student = new Student(); System.out.println("name? " + student.name); System.out.println("age? " + student.age); System.out.println("isScienceMajor? " + student.isScienceMajor); System.out.println("gender? " + student.gender); } Output: name? null age? 0 isScienceMajor? false gender? 00

36 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); } Compile error: variable not initialized

37 Differences between Variables of Primitive Data Types and Object Types
Primitive type int i = i 1 Object type Circle c c reference c: Circle radius = 1 Created using: myCircle = new Circle(1.0);

38 Copying Variables of Primitive Data Types and Object Types

39 On the previous slide, after the assignment statement
c1 = c2; //circle objects c1 points to the same object referenced by c2. The object previously referenced by c1 is no longer referenced/accessible (i.e., garbage). Garbage is automatically collected by JVM. TIP: If you know that an object is no longer needed, you can explicitly assign null to a reference variable for the object. The JVM will automatically collect the space if the object is not referenced by any variable in the program.

40 The Date Class Java provides a system-independent encapsulation of date and time in the java.util.Date class. You can use the Date class to create an instance for the current date and time and use its toString method to return the date and time as a string.

41 The Date Class Example For example, the following code
java.util.Date date = new java.util.Date(); System.out.println(date.toString()); displays a string like Sun Mar 09 13:50:19 EST 2003.

42 The Random Class You have used Math.random() to obtain a random double value between 0.0 and 1.0 (excluding 1.0). A more useful random number generator is provided in the java.util.Random class.

43 The Random Class Example
If two Random objects have the same seed, they will generate identical sequences of numbers. For example, the following code creates two Random objects with the same seed 3. Random random1 = new Random(3); System.out.print("From random1: "); for (int i = 0; i < 10; i++) System.out.print(random1.nextInt(1000) + " "); Random random2 = new Random(3); System.out.print("\nFrom random2: "); System.out.print(random2.nextInt(1000) + " "); From random1: From random2:

44 The Point2D Class Java API has a conveninent Point2D class in the javafx.geometry package for representing a point in a two-dimensional plane. TestPoint2D Run

45 Instance Variables, and Methods
Instance variables belong to a specific instance. Instance methods are invoked by an instance of the class.

46 Static Variables, Constants, and Methods
Static variables are shared by all the objects of the class. Static methods are not tied to a specific object, applied to all objects of the class. Static constants (final variables) are shared by all the objects of the class. To declare static variables, constants, and methods, use the static modifier.

47 Static Variables, Constants, and Methods, cont.

48 1  public class CircleWithStaticMembers {
2   /** The radius of the circle */ 3   double radius; 4   5   /** The number of the objects created */ 6   static int numberOfObjects = 0; 7   8   /** Construct a circle with radius 1 */ 9   CircleWithStaticMembers() { 10   radius = 1.0; 11   numberOfObjects++; 12   } 13   14   /** Construct a circle with a specified radius */ 15   CircleWithStaticMembers(double newRadius) { 16   radius = newRadius; 17   numberOfObjects++; 18   } 19   20   /** Return numberOfObjects */ 21   static int getNumberOfObjects() { 22   return numberOfObjects; 23   } 24   25   /** Return the area of this circle */ 26   double getArea() { 27   return radius * radius * Math.PI; 28   } 29  }

49 1  public class TestCircleWithStaticMembers {
2   /** Main method */ 3   public static void main(String[] args) { 4   System.out.println("Before creating objects"); 5   System.out.println("The number of Circle objects is " + 6   CircleWithStaticMembers.numberOfObjects); 7   8   // Create c1 9   CircleWithStaticMembers c1 = new CircleWithStaticMembers(); 10   11   // Display c1 BEFORE c2 is created 12   System.out.println("\nAfter creating c1"); 13   System.out.println("c1: radius (" + c1.radius + 14   ") and number of Circle objects (" + 15   c1.numberOfObjects + ")"); 16  

50 17   // Create c2 18   CircleWithStaticMembers c2 = new CircleWithStaticMembers(5); 19   20   // Modify c1 21   c1.radius = 9; 22   23   // Display c1 and c2 AFTER c2 was created 24   System.out.println("\nAfter creating c2 and modifying c1"); 25   System.out.println("c1: radius (" + c1.radius + 26   ") and number of Circle objects (" + 27   c1.numberOfObjects + ")"); 28   System.out.println("c2: radius (" + c2.radius + 29   ") and number of Circle objects (" + 30   c2.numberOfObjects + ")"); 31   } 32  }

51 Static and Instance Members Relationship

52 1 public class A { 2 int i = 5; 3 static int k = 2; 4 5 public static void main(String[] args) { 6 int j = i; // Wrong because i is an instance variable 7 m1(); // Wrong because m1() is an instance method 8 } 9 10 public void m1() { 11 // Correct since instance and static variables and methods 12 // can be used in an instance method 13 i = i + k + m2(i, k); 14 } 15 16 public static int m2(int i, int j) { 17 return (int)(Math.pow(i, j)); 18 } 19 }

53 1 public class A { 2 int i = 5; 3 static int k = 2; 4 5 public static void main(String[] args) { 6 A a = new A(); 7 int j = a.i; // OK, a.i accesses the object's instance variable 8 a.m1(); // OK, a.m1() invokes the object's instance method 9 } 10 11 public void m1() { 12 i = i + k + m2(i, k); 13 } 14 15 public static int m2(int i, int j) { 16 return (int)(Math.pow(i, j)); 17 } 18 }

54 Visibility Modifiers and Accessor/Mutator Methods
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.

55 The private modifier restricts access to within a class,
the default modifier restricts access to within a package, the public modifier enables unrestricted access.

56 The default modifier on a class restricts access to within a package, and the public modifier enables unrestricted access.

57 Why Data Fields Should Be private?
To protect data. To make code easy to maintain and update.. How? Always use private variables! Encapsulation is the idea of hiding the class internal details that are not required by clients/users of the class.

58 Visibility Modifiers - Comments - 1
Class members (variables or methods) that are declared with public visibility can be referenced/accessed anywhere in the program. Class members that are declared with private visibility can be referenced/accessed only within that class. Class members declared without a visibility modifier have default visibility and can be referenced/accessed by any class in the same package. Public variables violate encapsulation because they allow class clients to “reach in” and modify the values directly. Therefore instance variables should not be declared with public visibility.

59 Visibility Modifiers - Comments - 2
Methods that provide the object's services must be declared with public visibility so that they can be invoked by clients (users of the object). Public methods are also called service methods. A method created simply to assist a service method is called a support method. Since a support method is not intended to be called by a client, it should be declared with private visibility.

60 Example of Data Field Encapsulation
CircleWithPrivateDataFields TestCircleWithPrivateDataFields Run

61 public class CircleWithPrivateDataFields { private double radius = 1; private static int numberOfObjects = 0; public CircleWithPrivateDataFields() { numberOfObjects++; } public CircleWithPrivateDataFields(double newRadius) { radius = newRadius; numberOfObjects++; } public double getRadius() { return radius; } public void setRadius(double newRadius) { radius = (newRadius >= 0) ? newRadius : 0; //no negative radius } public static int getNumberOfObjects() {return numberOfObjects; } public double getArea() {return radius*radius*Math.PI; } }

62 public class TestCircleWithPrivateDataFields { public static void main(String[] args) { // Main method // Create a Circle with radius CircleWithPrivateDataFields myCircle = new CircleWithPrivateDataFields(10.0); System.out.println("The area of the circle of radius " myCircle.getRadius() + " is " + myCircle.getArea()); // Increase myCircle's radius by 10% myCircle.setRadius(myCircle.getRadius() * 1.1); System.out.println("The area of the circle of radius " myCircle.getRadius() + " is " + myCircle.getArea()); } } Note: variable radius cannot be directly accessed Only through the class methods! Output: The area of the circle of radius 10.0 is The area of the circle of radius 11.0 is

63 Passing Objects to Methods
Passing by value for primitive type value (the value is passed to the parameter) the actual value is copied into the formal parameter. Passing by value for reference type value (the value is the reference to the object) The reference value (memory address) is passed (copied) to the actual parameter, not the object itself. Any changes to the passed reference will be reflected on the object outside the method (similar to passing strings and arrays).

64 Passing Objects to Methods, cont.

65 1  public class TestPassObject {
2   /** Main method */ 3   public static void main(String[] args) { 4   // Create a Circle object with radius 1 5   CircleWithPrivateDataFields myCircle = 6   new CircleWithPrivateDataFields(1); 7   8   // Print areas for radius 1, 2, 3, 4, and 5. 9   int n = 5; 10   printAreas(myCircle, n); 11   12   // See myCircle.radius and times 13   System.out.println("\n" + "Radius is " + myCircle.getRadius()); 14   System.out.println("n is " + n); 15   } 16   17   /** Print a table of areas for radius */ 18   public static void printAreas( 19   CircleWithPrivateDataFields c, int times) { 20   System.out.println("Radius \t\tArea"); 21   while (times >= 1) { 22   System.out.println(c.getRadius() + "\t\t" + c.getArea()); 23   c.setRadius(c.getRadius() + 1); 24   times--; 25   } 26   } 27  }

66 Array of Objects Consider:
Circle[] circleArray = new Circle[10]; An array of objects is actually an array of reference variables. Thus, invoking circleArray[1].getArea() involves two levels of referencing: circleArray references the entire array circleArray[1] references a Circle object See next slide.

67 Array of Objects, cont. Circle[] circleArray = new Circle[10];
Memory space for the array Heap space for the objects

68 public class TotalArea { public static void main(String[] args) { CircleWithPrivateDataFields[] circleArray; //Declare circleArray circleArray = createCircleArray();//Create circleArray //Print circleArray and total areas of the circles printCircleArray(circleArray); } //Create an array of Circle objects public static CircleWithPrivateDataFields[] createCircleArray() { CircleWithPrivateDataFields[] circleArray = new CircleWithPrivateDataFields[5]; for (int i = 0; i < circleArray.length; i++) { circleArray[i] = new CircleWithPrivateDataFields(Math.random() * 100); } return circleArray; //Return Circle array } // next slide

69 //Print an array of circles and their total area public static void printCircleArray( CircleWithPrivateDataFields[] circleArray) { System.out.println("Radius" + "\t\t\t\t" + "Area"); for (int i = 0; i < circleArray.length; i++) { System.out.println(circleArray[i].getRadius() + "\t\t" circleArray[i].getArea()); } System.out.println(" "); //Compute and display the result System.out.println("The total areas of circles is\t" sum(circleArray)); } public static double sum( //Static method to add circle areas CircleWithPrivateDataFields[] circleArray) { double sum = 0; //Initialize sum for (int i = 0; i < circleArray.length; i++)//Add areas to sum sum = sum + circleArray[i].getArea(); return sum; } }

70 Output: ----jGRASP exec: java TotalArea Radius Area The total areas of circles is jGRASP: operation complete.

71 Immutable Objects and Classes
If the contents of an object cannot be changed once it is created, the object is called an immutable object and its class is called an immutable class. For example, If you delete the set method in the Circle class, the class would be immutable (not changeable) because radius is private and cannot be changed without a set method. A class with all private data fields and without mutators (set methods) is not necessarily immutable. For example, the following class Student has all private data fields and no mutators, but it is mutable (changeable).

72 Example 1 public class Student { 2 private int id;
3 private String name; 4 private java.util.Date dateCreated; 5 6 public Student(int ssn, String newName) { id = ssn; name = newName; dateCreated = new java.util.Date(); 10 } 11 12 public int getId() { return id; 14 } 15 16 public String getName() { return name; 18 } 19 20 public java.util.Date getDateCreated() { return dateCreated; 22 } 23 } Example public class Test { public static void main(String[] args) { Student student = new Student( , "John"); java.util.Date dateCreated = student.getDateCreated(); dateCreated.setTime(200000); // Now dateCreated field is changed! }

73 What Class is Immutable?
For a class to be immutable, it must meet the following requirements: All data fields must be private. There can’t be any mutator methods for data fields. No accessor methods can return a reference to a data field that is mutable (changeable).

74 Scope of Variables The scope of instance and static variables is the entire class. They can be declared anywhere inside a class. A class’s variables and methods can appear in any order in the class The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be initialized explicitly before it can be used.

75 Example What is the output for f.p(), where f is an instance of F?
public class F { private int x = 0; // Instance variable private int y = 0; public F() { } public void p() { int x = 1; // Local variable System.out.println("x = " + x); System.out.println("y = " + y); What is the output for f.p(), where f is an instance of F?

76 The this Keyword The this keyword is the name of a reference that refers to an object itself. One common use of the this keyword is reference a class’s hidden data fields. Another common use of the this keyword to enable a constructor to invoke another constructor of the same class.

77 Reference the Hidden Data Fields

78 Calling Overloaded Constructor

79 End of Chapter 9


Download ppt "Chapter 9 Objects and Classes"

Similar presentations


Ads by Google