Presentation is loading. Please wait.

Presentation is loading. Please wait.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 OBJECTS –ORIENTED PROGRAMMING.

Similar presentations


Presentation on theme: "Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 OBJECTS –ORIENTED PROGRAMMING."— Presentation transcript:

1 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 OBJECTS –ORIENTED PROGRAMMING Chapter II 1

2 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 2 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. 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 of an object is defined by a set of methods.

3 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 3 Objects An object has both a state and behavior. The state defines the object, and the behavior defines what the object does.

4 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 4 Classes Classes are constructs that define objects of the same type. A Java class uses variables to define data fields and methods to define behaviors. Additionally, a class provides a special type of methods, known as constructors, which are invoked to construct objects from the class.

5 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 5 Classes

6 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 6 UML Class Diagram

7 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 7 Constructors Circle() { } Circle(double newRadius) { radius = newRadius; } Constructors are a special kind of methods that are invoked to construct objects.

8 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 8 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.

9 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 9 Creating Objects Using Constructors new ClassName(); Example: new Circle(); new Circle(5.0);

10 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 10 Default Constructor A class may be declared without constructors. In this case, a no-arg constructor with an empty body is implicitly declared in the class. This constructor, called a default constructor, is provided automatically only if no constructors are explicitly declared in the class.

11 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 11 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;

12 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 12 Declaring/Creating Objects in a Single Step ClassName objectRefVar = new ClassName(); Example: Circle myCircle = new Circle(); Create an object Assign object reference

13 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 13 Accessing Objects F Referencing the object’s data: objectRefVar.data e.g., myCircle.radius F Invoking the object’s method: objectRefVar.methodName(arguments) e.g., myCircle.getArea()

14 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 14 A Simple Circle Class  Objective: Demonstrate creating objects, accessing data, and using methods. TestCircle1 Run

15 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 15 Trace Code Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; reference value myCircle reference value yourCircle Change radius in yourCircle

16 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 16 Caution Recall that you use 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()? The answer is no. All the methods used before this chapter are static methods, which are defined using the static keyword. However, getArea() is non-static. It must be invoked from an object using objectRefVar.methodName(arguments) (e.g., myCircle.getArea()). More explanations will be given in Section 7.7, “Static Variables, Constants, and Methods.”

17 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 17 Reference Data Fields The data fields can be of reference types. For example, the following Student class contains a data field name of the String type. 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; // c has default value '\u0000' }

18 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 18 The null Value If a data field of a reference type does not reference any object, the data field holds a special literal value, null.

19 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 19 Default Value for a Data Field 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. 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); }

20 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 20 Example 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 Java assigns no default value to a local variable inside a method.

21 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 21 Differences between Variables of Primitive Data Types and Object Types

22 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 22 Copying Variables of Primitive Data Types and Object Types

23 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 23 Garbage Collection As shown in the previous figure, after the assignment statement c1 = c2, c1 points to the same object referenced by c2. The object previously referenced by c1 is no longer referenced. This object is known as garbage. Garbage is automatically collected by JVM.

24 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 24 Garbage Collection, cont 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.

25 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 25 Instance Variables, and Methods Instance variables belong to a specific instance. Instance methods are invoked by an instance of the class.

26 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 26 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.

27 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 27 Static Variables, Constants, and Methods, cont. To declare static variables, constants, and methods, use the static modifier.

28 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 28 Static Variables, Constants, and Methods, cont.

29 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 29 Example of Using Instance and Class Variables and Method Objective: Demonstrate the roles of instance and class variables and their uses. This example adds a class variable numberOfObjects to track the number of Circle objects created. TestCircle2Run Circle2

30 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 30 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.

31 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 31 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.

32 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 32 NOTE The private member of an object cannot be accessed outside of its class.

33 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 33 Why Data Fields Should Be private? To protect data. To make class easy to maintain.

34 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 34 Example of Data Field Encapsulation Circle3 RunTestCircle3

35 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 35 Immutable Objects and Classes If the contents of an object cannot be changed once the object is created, the object is called an immutable object and its class is called an immutable class. If you delete the set method in the Circle class in the preceding example, the class would be immutable because radius is private and cannot be changed without a set method. 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.

36 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 36 Example public class Student { private int id; private BirthDate birthDate; public Student(int ssn, int year, int month, int day) { id = ssn; birthDate = new BirthDate(year, month, day); } public int getId() { return id; } public BirthDate getBirthDate() { return birthDate; } } public class BirthDate { private int year; private int month; private int day; public BirthDate(int newYear, int newMonth, int newDay) { year = newYear; month = newMonth; day = newDay; } public void setYear(int newYear) { year = newYear; } } 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! } }

37 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 37 What Class is Immutable? For a class to be immutable, it must mark all data fields private and provide no mutator methods and no accessor methods that would return a reference to a mutable data field object.

38 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 38 Passing Objects to Methods F Passing by value for primitive type value (the value is passed to the parameter) F Passing by value for reference type value (the value is the reference to the object) TestPassObject Run

39 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 39 Passing Objects to Methods, cont.

40 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 40 Scope of Variables F The scope of instance and static variables is the entire class. They can be declared anywhere inside a class. F 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.

41 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 41 The this Keyword F Use this to refer to the object that invokes the instance method. F Use this to refer to an instance data field. F Use this to invoke an overloaded constructor of the same class.

42 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 42 Serving as Proxy to the Calling Object

43 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 43 Calling Overloaded Constructor

44 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 44 Class Abstraction and Encapsulation Class abstraction means to separate class implementation from the use of the class. The creator of the class provides a description of the class and let the user know how the class can be used. The user of the class does not need to know how the class is implemented. The detail of implementation is encapsulated and hidden from the user.

45 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 45 Example: The Loan Class TestLoanClass RunLoan

46 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 46 Example: The Course Class TestCourceRunCourse

47 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 47 Example: The StackOfIntegers Class Run TestStackOfIntegers

48 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 48 Implementing StackOfIntegers Class StackOfIntegers

49 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 INHERITANCE AND POLYMORPHISM 49

50 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 50 Superclasses and Subclasses GeometricObject Circle Rectangle TestCircleRectangle Run

51 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 51 Are superclass’s Constructor Inherited? No. They are not inherited. They are invoked explicitly or implicitly. Explicitly using the super keyword. A constructor is used to construct an instance of a class. Unlike properties and methods, a superclass's constructors are not inherited in the subclass. They can only be invoked from the subclasses' constructors, using the keyword super. If the keyword super is not explicitly used, the superclass's no-arg constructor is automatically invoked.

52 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 52 Superclass’s Constructor Is Always Invoked A constructor may invoke an overloaded constructor or its superclass’s constructor. If none of them is invoked explicitly, the compiler puts super() as the first statement in the constructor. For example,

53 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 53 Using the Keyword super F To call a superclass constructor F To call a superclass method The keyword super refers to the superclass of the class in which super appears. This keyword can be used in two ways:

54 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 54 CAUTION You must use the keyword super to call the superclass constructor. Invoking a superclass constructor’s name in a subclass causes a syntax error. Java requires that the statement that uses the keyword super appear first in the constructor.

55 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 55 Constructor Chaining public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } Constructing an instance of a class invokes all the superclasses’ constructors along the inheritance chain. This is called constructor chaining.

56 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 56 Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } 1. Start from the main method animation

57 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 57 Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } 2. Invoke Faculty constructor animation

58 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 58 Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } 3. Invoke Employee’s no- arg constructor animation

59 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 59 Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } 4. Invoke Employee(String) constructor animation

60 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 60 Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } 5. Invoke Person() constructor animation

61 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 61 Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } 6. Execute println animation

62 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 62 Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } 7. Execute println animation

63 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 63 Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } 8. Execute println animation

64 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 64 Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } 9. Execute println animation

65 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 65 Example on the Impact of a Superclass without no-arg Constructor public class Apple extends Fruit { } class Fruit { public Fruit(String name) { System.out.println("Fruit's constructor is invoked"); } Find out the errors in the program:

66 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 66 Declaring a Subclass A subclass extends properties and methods from the superclass. You can also: F Add new properties F Add new methods F Override the methods of the superclass

67 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 67 Calling Superclass Methods You could rewrite the printCircle() method in the Circle class as follows: public void printCircle() { System.out.println("The circle is created " + super.getDateCreated() + " and the radius is " + radius); }

68 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 68 Overriding Methods in the Superclass A subclass inherits methods from a superclass. Sometimes it is necessary for the subclass to modify the implementation of a method defined in the superclass. This is referred to as method overriding. public class Circle extends GeometricObject { // Other methods are omitted /** Override the toString method defined in GeometricObject */ public String toString() { return super.toString() + "\nradius is " + radius; }

69 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 69 NOTE An instance method can be overridden only if it is accessible. Thus a private method cannot be overridden, because it is not accessible outside its own class. If a method defined in a subclass is private in its superclass, the two methods are completely unrelated.

70 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 70 NOTE Like an instance method, a static method can be inherited. However, a static method cannot be overridden. If a static method defined in the superclass is redefined in a subclass, the method defined in the superclass is hidden.

71 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 71 Overriding vs. Overloading

72 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 72 The Object Class Every class in Java is descended from the java.lang.Object class. If no inheritance is specified when a class is defined, the superclass of the class is Object.

73 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 73 The toString() method in Object The toString() method returns a string representation of the object. The default implementation returns a string consisting of a class name of which the object is an instance, the at sign (@), and a number representing this object. Loan loan = new Loan(); System.out.println(loan.toString()); The code displays something like Loan@15037e5. This message is not very helpful or informative. Usually you should override the toString method so that it returns a digestible string representation of the object.

74 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 74 Polymorphism, Dynamic Binding and Generic Programming public class PolymorphismDemo { public static void main(String[] args) { m(new GraduateStudent()); m(new Student()); m(new Person()); m(new Object()); } public static void m(Object x) { System.out.println(x.toString()); } class GraduateStudent extends Student { } class Student extends Person { public String toString() { return "Student"; } class Person extends Object { public String toString() { return "Person"; } Method m takes a parameter of the Object type. You can invoke it with any object. An object of a subtype can be used wherever its supertype value is required. This feature is known as polymorphism. When the method m(Object x) is executed, the argument x’s toString method is invoked. x may be an instance of GraduateStudent, Student, Person, or Object. Classes GraduateStudent, Student, Person, and Object have their own implementation of the toString method. Which implementation is used will be determined dynamically by the Java Virtual Machine at runtime. This capability is known as dynamic binding. Polymorphism Demo Run

75 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 75 Dynamic Binding Dynamic binding works as follows: Suppose an object o is an instance of classes C 1, C 2,..., C n-1, and C n, where C 1 is a subclass of C 2, C 2 is a subclass of C 3,..., and C n-1 is a subclass of C n. That is, C n is the most general class, and C 1 is the most specific class. In Java, C n is the Object class. If o invokes a method p, the JVM searches the implementation for the method p in C 1, C 2,..., C n-1 and C n, in this order, until it is found. Once an implementation is found, the search stops and the first-found implementation is invoked.

76 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 76 Method Matching vs. Binding Matching a method signature and binding a method implementation are two issues. The compiler finds a matching method according to parameter type, number of parameters, and order of the parameters at compilation time. A method may be implemented in several subclasses. The Java Virtual Machine dynamically binds the implementation of the method at runtime. See Review Questions 9.7 and 9.9.

77 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 77 Generic Programming public class PolymorphismDemo { public static void main(String[] args) { m(new GraduateStudent()); m(new Student()); m(new Person()); m(new Object()); } public static void m(Object x) { System.out.println(x.toString()); } class GraduateStudent extends Student { } class Student extends Person { public String toString() { return "Student"; } class Person extends Object { public String toString() { return "Person"; } Polymorphism allows methods to be used generically for a wide range of object arguments. This is known as generic programming. If a method’s parameter type is a superclass (e.g., Object), you may pass an object to this method of any of the parameter’s subclasses (e.g., Student or String). When an object (e.g., a Student object or a String object) is used in the method, the particular implementation of the method of the object that is invoked (e.g., toString) is determined dynamically.

78 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 78 Casting Objects You have already used the casting operator to convert variables of one primitive type to another. Casting can also be used to convert an object of one class type to another within an inheritance hierarchy. In the preceding section, the statement m(new Student()); assigns the object new Student() to a parameter of the Object type. This statement is equivalent to: Object o = new Student(); // Implicit casting m(o); The statement Object o = new Student(), known as implicit casting, is legal because an instance of Student is automatically an instance of Object.

79 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 79 Why Casting Is Necessary? Suppose you want to assign the object reference o to a variable of the Student type using the following statement: Student b = o; A compilation error would occur. Why does the statement Object o = new Student() work and the statement Student b = o doesn’t? This is because a Student object is always an instance of Object, but an Object is not necessarily an instance of Student. Even though you can see that o is really a Student object, the compiler is not so clever to know it. To tell the compiler that o is a Student object, use an explicit casting. The syntax is similar to the one used for casting among primitive data types. Enclose the target object type in parentheses and place it before the object to be cast, as follows: Student b = (Student)o; // Explicit casting

80 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 80 Casting from Superclass to Subclass Explicit casting must be used when casting an object from a superclass to a subclass. This type of casting may not always succeed. Apple x = (Apple)fruit; Orange x = (Orange)fruit;

81 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 81 The instanceof Operator Use the instanceof operator to test whether an object is an instance of a class: Object myObject = new Circle();... // Some lines of code /** Perform casting if myObject is an instance of Circle */ if (myObject instanceof Circle) { System.out.println("The circle diameter is " + ((Circle)myObject).getDiameter());... }

82 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 82 TIP To help understand casting, you may also consider the analogy of fruit, apple, and orange with the Fruit class as the superclass for Apple and Orange. An apple is a fruit, so you can always safely assign an instance of Apple to a variable for Fruit. However, a fruit is not necessarily an apple, so you have to use explicit casting to assign an instance of Fruit to a variable of Apple.

83 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 83 Example: Demonstrating Polymorphism and Casting This example creates two geometric objects: a circle, and a rectangle, invokes the displayGeometricObject method to display the objects. The displayGeometricObject displays the area and diameter if the object is a circle, and displays area if the object is a rectangle. TestPolymorphismCastingRun

84 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 84 The protected Modifier  The protected modifier can be applied on data and methods in a class. A protected data or a protected method in a public class can be accessed by any class in the same package or its subclasses, even if the subclasses are in a different package. F private, default, protected, public

85 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 85 Accessibility Summary

86 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 86 Visibility Modifiers

87 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 87 A Subclass Cannot Weaken the Accessibility A subclass may override a protected method in its superclass and change its visibility to public. However, a subclass cannot weaken the accessibility of a method defined in the superclass. For example, if a method is defined as public in the superclass, it must be defined as public in the subclass.

88 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 88 NOTE The modifiers are used on classes and class members (data and methods), except that the final modifier can also be used on local variables in a method. A final local variable is a constant inside a method.

89 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 89 The final Modifier  The final class cannot be extended: final class Math {... }  The final variable is a constant: final static double PI = 3.14159;  The final method cannot be overridden by its subclasses.

90 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 90 The equals() and hashCode() Methods in the Object Class F The equals() method compares the contents of two objects. F The hashCode() method returns the hash code of the object. Hash code is an integer, which can be used to store the object in a hash set so that it can be located quickly. Optional

91 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 91 The equals Method The equals() method compares the contents of two objects. The default implementation of the equals method in the Object class is as follows: public boolean equals(Object obj) { return (this == obj); } For example, the equals method is overridden in the Circle class. public boolean equals(Object o) { if (o instanceof Circle) { return radius == ((Circle)o).radius; } else return false; } Optional

92 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 92 NOTE The == comparison operator is used for comparing two primitive data type values or for determining whether two objects have the same references. The equals method is intended to test whether two objects have the same contents, provided that the method is modified in the defining class of the objects. The == operator is stronger than the equals method, in that the == operator checks whether the two reference variables refer to the same object.

93 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 93 The hashCode() method Invoking hashCode() on an object returns the hash code of the object. Hash code is an integer, which can be used to store the object in a hash set so that it can be located quickly. Hash sets will be introduced in Chapter 22, “Java Collections Framework.” The hashCode implemented in the Object class returns the internal memory address of the object in hexadecimal. Your class should override the hashCode method whenever the equals method is overridden. By contract, if two objects are equal, their hash codes must be same. Optional

94 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 94 The finalize, clone, and getClass Methods F The finalize method is invoked by the garbage collector on an object when the object becomes garbage. F The clone() method copies an object. F The getClass() method returns an instance of the java.lang.Class class, which contains the information about the class for the object. Before an object is created, its defining class is loaded and the JVM automatically creates an instance of java.lang.Class for the class. From this instance, you can discover the information about the class at runtime. Optional

95 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 95 The finalization Demo The finalize method is invoked by the JVM. You should never write the code to invoke it in your program. For this reason, the protected modifier is appropriate. Optional FinalizationDemoRun

96 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 96 Hiding Fields and Static Methods You can override an instance method, but you cannot override a field (instance or static) or a static method. If you declare a field or a static method in a subclass with the same name as one in the superclass, the one in the superclass is hidden, but it still exists. The two fields or static methods are independent. You can reference the hidden field or static method using the super keyword in the subclass. The hidden field or method can also be accessed via a reference variable of the superclass’s type. Optional

97 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 97 Hiding Fields and Static Methods, cont. When invoking an instance method from a reference variable, the actual class of the object referenced by the variable decides which implementation of the method is used at runtime. When accessing a field or a static method, the declared type of the reference variable decides which method is used at compilation time. HidingDemoRun Optional

98 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 98 Initialization Block Initialization blocks can be used to initialize objects along with the constructors. An initialization block is a block of statements enclosed inside a pair of braces. An initialization block appears within the class declaration, but not inside methods or constructors. It is executed as if it were placed at the beginning of every constructor in the class. Optional

99 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 99 Static Initialization Block A static initialization block is much like a nonstatic initialization block except that it is declared static, can only refer to static members of the class, and is invoked when the class is loaded. The JVM loads a class when it is needed. A superclass is loaded before its subclasses. InitializationDemoRun Optional

100 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 100 Inheriting GUI Components F Objective: Create a custom frame by extending JFrame. CustomFrame Run Optional GUI

101 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 ABSTRACT CLASSES AND INTERFACES 101

102 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 102 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses  The abstract method –Method signature without implementation

103 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 103

104 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 104 Abstract Classes GeometricObject Circle Rectangle

105 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 105 NOTE An abstract method cannot be contained in a nonabstract class. If a subclass of an abstract superclass does not implement all the abstract methods, the subclass must be declared abstract. In other words, in a nonabstract subclass extended from an abstract class, all the abstract methods must be implemented, even if they are not used in the subclass.

106 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 106 NOTE An abstract class cannot be instantiated using the new operator, but you can still define its constructors, which are invoked in the constructors of its subclasses. For instance, the constructors of GeometricObject are invoked in the Circle class and the Rectangle class.

107 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 107 NOTE A class that contains abstract methods must be abstract. However, it is possible to declare an abstract class that contains no abstract methods. In this case, you cannot create instances of the class using the new operator. This class is used as a base class for defining a new subclass.

108 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 108 NOTE A subclass can be abstract even if its superclass is concrete. For example, the Object class is concrete, but its subclasses, such as GeometricObject, may be abstract.

109 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 109 NOTE A subclass can override a method from its superclass to declare it abstract. This is rare, but useful when the implementation of the method in the superclass becomes invalid in the subclass. In this case, the subclass must be declared abstract.

110 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 110 NOTE You cannot create an instance from an abstract class using the new operator, but an abstract class can be used as a data type. Therefore, the following statement, which creates an array whose elements are of GeometricObject type, is correct. GeometricObject[] geo = new GeometricObject[10];

111 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 111 Example: Using the GeometricObject Class F Objective: This example creates two geometric objects: a circle, and a rectangle, invokes the equalArea method to check if the two objects have equal area, and invokes the displayGeometricObject method to display the objects. TestGeometricObject Run

112 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 112 The Abstract Calendar Class and Its GregorianCalendar subclass

113 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 113 The Abstract Calendar Class and Its GregorianCalendar subclass An instance of java.util.Date represents a specific instant in time with millisecond precision. java.util.Calendar is an abstract base class for extracting detailed information such as year, month, date, hour, minute and second from a Date object. Subclasses of Calendar can implement specific calendar systems such as Gregorian calendar, Lunar Calendar and Jewish calendar. Currently, java.util.GregorianCalendar for the Gregorian calendar is supported in the Java API.

114 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 114 The GregorianCalendar Class You can use new GregorianCalendar() to construct a default GregorianCalendar with the current time and use new GregorianCalendar(year, month, date) to construct a GregorianCalendar with the specified year, month, and date. The month parameter is 0- based, i.e., 0 is for January.

115 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 115 The get Method in Calendar Class The get(int field) method defined in the Calendar class is useful to extract the value for a given time field. The time fields are defined as constants such as YEAR, MONTH, DATE, HOUR (for the 12-hour clock), HOUR_OF_DAY (for the 24-hour clock), MINUTE, SECOND, DAY_OF_WEEK (the day number within the current week with 1 for Sunday), DAY_OF_MONTH (same as the DATE value), DAY_OF_YEAR (the day number within the current year with 1 for the first day of the year), WEEK_OF_MONTH (the week number within the current month), and WEEK_OF_YEAR (the week number within the current year). For example, the following code

116 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 116 Interfaces An interface is a classlike construct that contains only constants and abstract methods. In many ways, an interface is similar to an abstract class, but an abstract class can contain variables and concrete methods as well as constants and abstract methods. To distinguish an interface from a class, Java uses the following syntax to declare an interface: public interface InterfaceName { constant declarations; method signatures; }

117 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 117 Interface is a Special Class An interface is treated like a special class in Java. Each interface is compiled into a separate bytecode file, just like a regular class. Like an abstract class, you cannot create an instance from an interface using the new operator, but in most cases you can use an interface more or less the same way you use an abstract class. For example, you can use an interface as a data type for a variable, as the result of casting, and so on.

118 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 118 Define Interfaces Suppose you want to design a generic method to find the larger of two objects. The objects can be students, dates, or circles. Since compare methods are different for different types of objects, you need to define a generic compare method to determine the order of the two objects. Then you can tailor the method to compare students, dates, or circles. For example, you can use student ID as the key for comparing students, radius as the key for comparing circles, and volume as the key for comparing dates. You can use an interface to define a generic compareTo method, as follows:

119 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 119 Example of an Interface // This interface is defined in // java. lang package package java.lang; public interface Comparable { public int compareTo(Object o); }

120 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 120 String and Date Classes Many classes (e.g., String and Date) in the Java library implement Comparable to define a natural order for the objects. If you examine the source code of these classes, you will see the keyword implements used in the classes, as shown below: new String() instanceof String new String() instanceof Comparable new java.util.Date() instanceof java.util.Date new java.util.Date() instanceof Comparable

121 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 121 Generic max Method The return value from the max method is of the Comparable type. So, you need to cast it to String or Date explicitly.

122 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 122 Declaring Classes to Implement Comparable You cannot use the max method to find the larger of two instances of Rectangle, because Rectangle does not implement Comparable. However, you can declare a new rectangle class that implements Comparable. The instances of this new class are comparable. Let this new class be named ComparableRectangle. ComparableRectangle ComparableRectangle rectangle1 = new ComparableRectangle(4, 5); ComparableRectangle rectangle2 = new ComparableRectangle(3, 6); System.out.println(Max.max(rectangle1, rectangle2));

123 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 123 Interfaces vs. Abstract Classes In an interface, the data must be constants; an abstract class can have all types of data. Each method in an interface has only a signature without implementation; an abstract class can have concrete methods. VariablesConstructorsMethods Abstract class No restrictionsConstructors are invoked by subclasses through constructor chaining. An abstract class cannot be instantiated using the new operator. No restrictions. InterfaceAll variables must be public static final No constructors. An interface cannot be instantiated using the new operator. All methods must be public abstract instance methods

124 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 124 Interfaces vs. Abstract Classes, cont. All data fields are public final static and all methods are public abstract in an interface. For this reason, these modifiers can be omitted, as shown below: A constant defined in an interface can be accessed using syntax InterfaceName.CONSTANT_NAME (e.g., T1.K).

125 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 125 Interfaces vs. Abstract Classes, cont. Suppose that c is an instance of Class2. c is also an instance of Object, Class1, Interface1, Interface1_1, Interface1_2, Interface2_1, and Interface2_2. All classes share a single root, the Object class, but there is no single root for interfaces. Like a class, an interface also defines a type. A variable of an interface type can reference any instance of the class that implements the interface. If a class extends an interface, this interface plays the same role as a superclass. You can use an interface as a data type and cast a variable of an interface type to its subclass, and vice versa.

126 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 126 Caution: conflict interfaces In rare occasions, a class may implement two interfaces with conflict information (e.g., two same constants with different values or two methods with same signature but different return type). This type of errors will be detected by the compiler.

127 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 127 Whether to use an interface or a class? Abstract classes and interfaces can both be used to model common features. How do you decide whether to use an interface or a class? In general, a strong is-a relationship that clearly describes a parent- child relationship should be modeled using classes. For example, a staff member is a person. So their relationship should be modeled using class inheritance. A weak is-a relationship, also known as an is-kind-of relationship, indicates that an object possesses a certain property. A weak is-a relationship can be modeled using interfaces. For example, all strings are comparable, so the String class implements the Comparable interface. You can also use interfaces to circumvent single inheritance restriction if multiple inheritance is desired. In the case of multiple inheritance, you have to design one as a superclass, and others as interface. See Chapter 10, “Object- Oriented Modeling,” for more discussions.

128 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 128 Creating Custom Interfaces public interface Edible { /** Describe how to eat */ public String howToEat(); } class Animal { } class Chicken extends Animal implements Edible { public String howToEat() { return "Fry it"; } } class Tiger extends Animal { } class abstract Fruit implements Edible { } class Apple extends Fruit { public String howToEat() { return "Make apple cider"; } } class Orange extends Fruit { public String howToEat() { return "Make orange juice"; } }

129 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 129 class Chicken extends Animal implements Edible, Comparable { int weight; public Chicken(int weight) { this.weight = weight; } public String howToEat() { return "Fry it"; } public int compareTo(Object o) { return weight – ((Chicken)o).weight; } } Implements Multiple Interfaces

130 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 130 Creating Custom Interfaces, cont. public interface Edible { /** Describe how to eat */ public String howToEat(); } public class TestEdible { public static void main(String[] args) { Object[] objects = {new Tiger(), new Chicken(), new Apple()}; for (int i = 0; i < objects.length; i++) showObject(objects[i]); } public static void showObject(Object object) { if (object instanceof Edible) System.out.println(((Edible)object).howToEat()); } }

131 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 131 The Cloneable Interfaces package java.lang; public interface Cloneable { } Marker Interface: An empty interface. A marker interface does not contain constants or methods. It is used to denote that a class possesses certain desirable properties. A class that implements the Cloneable interface is marked cloneable, and its objects can be cloned using the clone() method defined in the Object class.

132 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 132 Examples Many classes (e.g., Date and Calendar) in the Java library implement Cloneable. Thus, the instances of these classes can be cloned. For example, the following code Calendar calendar = new GregorianCalendar(2003, 2, 1); Calendar calendarCopy = (Calendar)calendar.clone(); System.out.println("calendar == calendarCopy is " + (calendar == calendarCopy)); System.out.println("calendar.equals(calendarCopy) is " + calendar.equals(calendarCopy)); displays calendar == calendarCopy is false calendar.equals(calendarCopy) is true

133 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 133 Implementing Cloneable Interface To declare a custom class that implements the Cloneable interface, the class must override the clone() method in the Object class. The following code declares a class named House that implements Cloneable and Comparable. House

134 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 134 Shallow vs. Deep Copy House house1 = new House(1, 1750.50); House house2 = (House)house1.clone();

135 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 135 Wrapper Classes F Boolean F Character F Short F Byte F Integer F Long F Float F Double NOTE: (1) The wrapper classes do not have no-arg constructors. (2) The instances of all wrapper classes are immutable, i.e., their internal values cannot be changed once the objects are created.

136 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 Object-Oriented Design 136

137 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 137 Software Development Process

138 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 138 Requirement Specification A formal process that seeks to understand the problem and document in detail what the software system needs to do. This phase involves close interaction between users and designers. Most of the examples in this book are simple, and their requirements are clearly stated. In the real world, however, problems are not well defined. You need to study a problem carefully to identify its requirements.

139 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 139 System Analysis Seeks to analyze the business process in terms of data flow, and to identify the system’s input and output. Part of the analysis entails modeling the system’s behavior. The model is intended to capture the essential elements of the system and to define services to the system.

140 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 140 System Design The process of designing the system’s components. This phase involves the use of many levels of abstraction to decompose the problem into manageable components, identify classes and interfaces, and establish relationships among the classes and interfaces.

141 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 141 Implementation The process of translating the system design into programs. Separate programs are written for each component and put to work together. This phase requires the use of a programming language like Java. The implementation involves coding, testing, and debugging.

142 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 142 Testing Ensures that the code meets the requirements specification and weeds out bugs. An independent team of software engineers not involved in the design and implementation of the project usually conducts such testing.

143 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 143 Deployment Deployment makes the project available for use. For a Java applet, this means installing it on a Web server; for a Java application, installing it on the client's computer.

144 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 144 Maintenance Maintenance is concerned with changing and improving the product. A software product must continue to perform and improve in a changing environment. This requires periodic upgrades of the product to fix newly discovered bugs and incorporate changes.

145 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 145 Relationships among Classes F Association F Aggregation F Composition F Inheritance

146 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 146 Association Association represents a general binary relationship that describes an activity between two classes. An association is usually represented as a data field in the class.

147 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 147 Association Between Same Class Association may exist between objects of the same class. For example, a person may have a supervisor.

148 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 148 Aggregation and Composition Aggregation is a special form of association, which represents an ownership relationship between two classes. Aggregation models the has-a relationship. If an object is exclusively owned by an aggregated object, the relationship between the object and its aggregated object is referred to as composition.

149 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 149 Representing Aggregation in Classes An aggregation relationship is usually represented as a data field in the aggregated class.

150 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 150 Inner Classes Translation If Name or Address is used in the Person class only, they can be declared as an inner class in Person. For example, public class Person { private Name name; private Address address;... class Name {... } class Address {... }

151 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 151 Inheritance Inheritance models the is-an-extension-of relationship between two classes.

152 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 152 Weak Inheritance Relationship A weak is-an-extension-of relationship can be represented using interfaces. For example, the weak is-an-extension-of relationship “students are comparable based on their grades” can be represented by implementing the Comparable interface, as follows:

153 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 153 Class Design 1. Identify classes for the system. 2. Describe attributes and methods in each class. 3. Establish relationships among classes. 4. Create classes.

154 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 154 Example 11.1 Borrowing Loans Name BorrowerPersonLoanAddress

155 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 155 Example 11.1 Borrowing Loans, cont. The following is a test program that uses the classes Name, Person, Address, Borrower, and Loan. BorrowLoan Run

156 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 156 Example 11.2 The Rational Class RationalRunTestRationalClass

157 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 157 Class Design Guidelines F Designing a Single Class. F Using Modifiers public, protected, private and static F Using Inheritance or Aggregation F Using Interfaces or Abstract Classes

158 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 158 Designing a Class F A class should describe a single entity or a set of similar operations. A single entity with too many responsibilities can be broken into several classes to separate responsibilities. The String class, StringBuffer class, and StringTokenizer class all deal with strings, for example, but have different responsibilities.

159 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 159 Designing a Class, cont. F Classes are usually designed for use by many different customers. To make a class useful in a wide range of applications, the class should provide a variety of ways for customization through properties and methods.

160 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 160 Designing a Class, cont. F Classes are designed for reuse. Users can incorporate classes in many different combinations, orders, and environments. Therefore, you should design a class that imposes no restrictions on what or when the user can do with it, design the properties to ensure that the user can set properties in any order, with any combination of values, and design methods to function independently of their order of occurrence.

161 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 161 Designing a Class, cont. F Provide a public no-arg constructor and override the equals method and the toString method defined in the Object class whenever possible.

162 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 162 Designing a Class, cont. F Follow standard Java programming style and naming conventions. Choose informative names for classes, data fields, and methods. Always place the data declaration before the constructor, and place constructors before methods. Always provide a constructor and initialize variables to avoid programming errors.

163 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 163 Using Visibility Modifiers F Each class can present two contracts – one for the users of the class and one for the extenders of the class. Make the fields private and accessor methods public if they are intended for the users of the class. Make the fields or method protected if they are intended for extenders of the class. The contract for the extenders encompasses the contract for the users. The extended class may increase the visibility of an instance method from protected to public, or change its implementation, but you should never change the implementation in a way that violates that contract.

164 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 164 Using Visibility Modifiers, cont. F A class should use the private modifier to hide its data from direct access by clients. You can use get methods and set methods to provide users with access to the private data, but only to private data you want the user to see or to modify. A class should also hide methods not intended for client use. The gcd method in the Rational class in Example 11.2, “The Rational Class,” is private, for example, because it is only for internal use within the class.

165 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 165 Using the static Modifier F A property that is shared by all the instances of the class should be declared as a static property.

166 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 166 Using Inheritance or Aggregation In general, the difference between inheritance and aggregation is the difference between the is-an-extension-of relationship and the has-a relationship. For example, an apple is fruit; thus, you would use inheritance to model the relationship between the classes Apple and Fruit. A person has a name; thus, you would use aggregation to model the relationship between the classes Person and Name.

167 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 167 Using Inheritance or Aggregation, cont. Sometimes, the choice between inheritance and aggregation is not obvious. For example, you have used inheritance to model the relationship between the classes Circle and Cylinder. One could argue that a cylinder consists of circles; thus, you might use aggregation to define the Cylinder class as follows:

168 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 168 Using Inheritance or Composition, cont. public class Cylinder { private Circle circle; /** Constructors */ /** Methods */ }

169 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 169 Using Inheritance or Aggregation, cont. Both designs are fine. Which one is preferred? If polymorphism is desirable, you need to use the inheritance design. If you don’t care about polymorphism, the aggregation design gives more flexibility because the classes are less dependent using aggregation than using inheritance.

170 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 170 Using Interfaces or Abstract Classes Both interfaces and abstract classes can be used to generalize common features. How do you decide whether to use an interface or a class? In general, a strong is-an-extension-of relationship that clearly describes a parent- child relationship should be modeled using classes.

171 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 171 Using Interfaces or Abstract Classes, cont. For example, since an orange is a fruit, their relationship should be modeled using class inheritance. A weak is-an- extension-of relationship, also known as an is-kind-of relationship, indicates that an object possesses a certain property. A weak is-an-extension-of relationship can be modeled using interfaces. For example, all strings are comparable, so the String class implements the Comparable interface. A circle or a rectangle is a geometric object, for example, so Circle can be designed as a subclass of GeometricObject. Circles are different and comparable based on their radius, for example, so Circle can implement the Comparable interface.

172 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 172 Using Interfaces or Abstract Classes, cont. Interfaces are more flexible than abstract classes, because a subclass can extend only one superclass, but implement any number of interfaces. However, interfaces cannot contain concrete methods. You can combine the virtues of interfaces and abstract classes by creating an interface with a companion abstract class that implements the interface. So you can use the interface or its companion class whichever is more convenient.

173 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 173 Sequence diagrams Sequence diagrams describe interactions among objects by depicting the time ordering of method invocations.

174 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 174 Sequence diagrams, cont.

175 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 175 Statechart diagrams Statechart diagrams describe flow of control of the object.

176 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 176 Statechart diagrams, cont.

177 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 177 Supplement P: Designing Generic Matrix Classes F Objective: This example gives a generic class for matrix arithmetic. This class implements matrix addition and multiplication common for all types of matrices. GenericMatrix

178 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 178 Example 11.3, cont.

179 Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 179 Example 11.3, cont. F Objective: This example gives two programs that utilize the GenericMatrix class for integer matrix arithmetic and rational matrix arithmetic. TestIntegerMatrix Run TestRationalMatrix Run RationalMatrix IntegerMatrix


Download ppt "Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 OBJECTS –ORIENTED PROGRAMMING."

Similar presentations


Ads by Google