Chapter 8 Inheritance and Polymorphism Liang Introduction to

  • Slides: 76
Download presentation
Chapter 8 Inheritance and Polymorphism 一切皆有缘起 Liang, Introduction to Java Programming, revised by Dai-kaiyu

Chapter 8 Inheritance and Polymorphism 一切皆有缘起 Liang, Introduction to Java Programming, revised by Dai-kaiyu 1

Objectives F F F F F To develop a subclass from a superclass through

Objectives F F F F F To develop a subclass from a superclass through inheritance (§ 8. 2). To invoke the superclass’s constructors and methods using the super keyword (§ 8. 3). To override methods in the subclass (§ 8. 4). To explore the useful methods (equals(Object), hash. Code(), to. String(), finalize(), clone(), and get. Class()) in the Object class (§ 8. 5, § 8. 11 Optional). To comprehend polymorphism, dynamic binding, and generic programming (§ 8. 6). To describe casting and explain why explicit downcasting is necessary (§ 8. 7). To understand the effect of hiding data fields and static methods (§ 8. 8 Optional). To restrict access to data and methods using the protected visibility modifier (§ 8. 9). To declare constants, unmodifiable methods, and nonextendable class using the final modifier (§ 8. 10). To initialize data using initialization blocks and distinguish between instance initialization and static initialization blocks (§ 8. 12 Optioanl). Liang, Introduction to Java Programming, revised by Dai-kaiyu 2

Introduction l Object-oriented ¡ Inheritance programming Software reusability l Classes are created from existing

Introduction l Object-oriented ¡ Inheritance programming Software reusability l Classes are created from existing ones l • Absorbing attributes and behaviors • Adding new capabilities ¡ Polymorphism Enables developers to write programs in general fashion l Helps add new capabilities to system l Liang, Introduction to Java Programming, revised by Dai-kaiyu 3

Introduction (cont. ) l Object-oriented ¡ Inheritance l programming Subclass inherits from superclass •

Introduction (cont. ) l Object-oriented ¡ Inheritance l programming Subclass inherits from superclass • Subclass usually adds instance variables and methods l Single vs. multiple inheritance • Java does not support multiple inheritance Interfaces (discussed later) achieve the same effect l “Is a” relationship ¡ Composition l “Has a” relationship Liang, Introduction to Java Programming, revised by Dai-kaiyu 4

Object relationships Composition • Whole-part –Existance of an object relies on another Liang, Introduction

Object relationships Composition • Whole-part –Existance of an object relies on another Liang, Introduction to Java Programming, revised by Dai-kaiyu 5

Superclasses and Subclasses l “Is a” Relationship ¡ Object l “is an” object of

Superclasses and Subclasses l “Is a” Relationship ¡ Object l “is an” object of another class Rectangle “is a” quadrilateral • Class Rectangle inherits from class Quadrilateral ¡ Form tree-like hierarchical structures Liang, Introduction to Java Programming, revised by Dai-kaiyu 6

Superclasses and Subclasses UML Diagram Liang, Introduction to Java Programming, revised by Dai-kaiyu 7

Superclasses and Subclasses UML Diagram Liang, Introduction to Java Programming, revised by Dai-kaiyu 7

// Cylinder. java: Class definition for describing Cylinder public class Cylinder extends Circle {

// Cylinder. java: Class definition for describing Cylinder public class Cylinder extends Circle { private double length = 1; /** Return length */ public double get. Length() { return length; } supertype subtype /** Set length */ public void set. Length(double length) { this. length = length; } /** Return the volume of this cylinder */ public double find. Volume() { return find. Area() * length; } } Liang, Introduction to Java Programming, revised by Dai-kaiyu 8

Cylinder cylinder = new Cylinder(); System. out. println("The length is " + cylinder. get.

Cylinder cylinder = new Cylinder(); System. out. println("The length is " + cylinder. get. Length()); System. out. println("The radius is " + cylinder. get. Radius()); System. out. println("The volume of the cylinder is " + cylinder. find. Volume()); System. out. println("The area of the circle is " + cylinder. find. Area()); The output is The The Pravate data fields and mothods will not be inherited in a subclass length is 1. 0 radius is 1. 0 volume of the cylinder is 3. 14159 area of the circle is 3. 14159 Liang, Introduction to Java Programming, revised by Dai-kaiyu 9

An inheritance hierarchy for university Community. Members. Community. Member is a direct superclass of

An inheritance hierarchy for university Community. Members. Community. Member is a direct superclass of Employee Community. Member is an indirect superclass of Faculty Liang, Introduction to Java Programming, revised by Dai-kaiyu 10

A portion of a Shape class hierarchy. Liang, Introduction to Java Programming, revised by

A portion of a Shape class hierarchy. Liang, Introduction to Java Programming, revised by Dai-kaiyu 11

Using the Keyword super The keyword super refers to the superclass of the class

Using the Keyword super The keyword super refers to the superclass of the class in which super appears. This keyword can be used in two ways: l To call a superclass constructor l To call a superclass method Liang, Introduction to Java Programming, revised by Dai-kaiyu 12

CAUTION luse the keyword super to call the superclass constructor. Invoking a superclass constructor’s

CAUTION luse the keyword super to call the superclass constructor. Invoking a superclass constructor’s name in a subclass causes a syntax error. l. Java requires that the statement that uses the keyword super appear first in the constructor. Liang, Introduction to Java Programming, revised by Dai-kaiyu 13

NOTE l. Unlike properties and methods, a superclass's constructors are not inherited in the

NOTE l. Unlike properties and methods, a superclass's constructors are not inherited in the subclass. l. They can only be invoked from the subclasses' constructors, using the keyword super. l. If the keyword super is not explicitly used, the superclass's no-arg constructor is automatically invoked. Liang, Introduction to Java Programming, revised by Dai-kaiyu 14

Superclass’s Constructor Is Always Invoked A constructor may invoke an overloaded constructor or its

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, Liang, Introduction to Java Programming, revised by Dai-kaiyu 15

Constructor Chaining Constructing an instance of a class invokes all the superclasses’ constructors along

Constructor Chaining Constructing an instance of a class invokes all the superclasses’ constructors along the inheritance chain. This is called constructor chaining. public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System. out. println("Faculty's no-arg constructor is invoked"); } } class Employee extends Person { public Employee() { this("Invoke Employee’s overloaded constructor"); System. out. println("Employee's no-arg constructor is invoked"); } public Employee(String s) { System. out. println(s); } } class Person { public Person() { System. out. println("Person's no-arg constructor is invoked"); Liang, Introduction to Java Programming, revised by Dai-kaiyu } } 16

Constructor Chaining Constructing an instance of a class invokes all the superclasses’ constructors along

Constructor Chaining Constructing an instance of a class invokes all the superclasses’ constructors along the inheritance chain. This is called 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"); } Liang, Introduction to Java Programming, revised by Dai-kaiyu } 17

Trace Execution public class Faculty extends Employee { public static void main(String[] args) {

Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } 1. Start from the main method 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"); } } Liang, Introduction to Java Programming, revised by Dai-kaiyu 18

Trace Execution public class Faculty extends Employee { public static void main(String[] args) {

Trace Execution public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } 2. Invoke Faculty constructor 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"); } } Liang, Introduction to Java Programming, revised by Dai-kaiyu 19

Trace Execution public class Faculty extends Employee { public static void main(String[] args) {

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"); } 3. Invoke Employee’s noarg constructor } 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"); } } Liang, Introduction to Java Programming, revised by Dai-kaiyu 20

Trace Execution public class Faculty extends Employee { public static void main(String[] args) {

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"); } } 4. Invoke Employee(String) constructor 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"); } } Liang, Introduction to Java Programming, revised by Dai-kaiyu 21

Trace Execution public class Faculty extends Employee { public static void main(String[] args) {

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); } } 5. Invoke Person() constructor class Person { public Person() { System. out. println("(1) Person's no-arg constructor is invoked"); } } Liang, Introduction to Java Programming, revised by Dai-kaiyu 22

Trace Execution public class Faculty extends Employee { public static void main(String[] args) {

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); } } 6. Execute println class Person { public Person() { System. out. println("(1) Person's no-arg constructor is invoked"); } } Liang, Introduction to Java Programming, revised by Dai-kaiyu 23

Trace Execution public class Faculty extends Employee { public static void main(String[] args) {

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); } } 7. Execute println class Person { public Person() { System. out. println("(1) Person's no-arg constructor is invoked"); } } Liang, Introduction to Java Programming, revised by Dai-kaiyu 24

Trace Execution public class Faculty extends Employee { public static void main(String[] args) {

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); } } 8. Execute println class Person { public Person() { System. out. println("(1) Person's no-arg constructor is invoked"); } } Liang, Introduction to Java Programming, revised by Dai-kaiyu 25

Trace Execution public class Faculty extends Employee { public static void main(String[] args) {

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"); } } 9. Execute println 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"); } } Liang, Introduction to Java Programming, revised by Dai-kaiyu 26

Example on the Impact of a Superclass without noarg Constructor Find out the errors

Example on the Impact of a Superclass without noarg Constructor Find out the errors in the program: public class Apple extends Fruit { } class Fruit { public Fruit(String name) { System. out. println("Fruit's constructor is invoked"); } } 1、a default no-arg constructor will be added only when no constructor are specified explicitly. (so Fruit class has no default constructor) 2、a class will call the default constructor of its superclass if no explicit calling(so Apple called the default constructor of 27 Fruit, but Fruit class has none such a default one) Liang, Introduction to Java Programming, revised by Dai-kaiyu

Declaring a Subclass A subclass extends properties and methods from the superclass. You can

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 Liang, Introduction to Java Programming, revised by Dai-kaiyu 28

Overriding Methods in the Superclass A subclass inherits methods from a superclass. Sometimes it

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. // Cylinder. java: New cylinder class that overrides the find. Area() // method defined in the circle class. public class Cylinder extends Circle { /** Return the surface area of this cylinder. The formula is * 2 * circle area + cylinder body area */ public double find. Area() { return 2 * super. find. Area() + 2 * get. Radius() * Math. PI * length; } // Other methods are omitted } Liang, Introduction to Java Programming, revised by Dai-kaiyu 29

Override vs Overload l. Overload: lsame name ldifferent signature (by parameters) l. Can have

Override vs Overload l. Overload: lsame name ldifferent signature (by parameters) l. Can have different return type l. Can have different modifier Compile error if two methods differ only in return type Liang, Introduction to Java Programming, revised by Dai-kaiyu 30

A Quiz public class Sample{ public void amethod(int i, String s){} } Which ones

A Quiz public class Sample{ public void amethod(int i, String s){} } Which ones can be added into the class A)public void amethod(String s, int i) { } () B)public int amethod(int i, String s) {return 0; } () C)private void amethod(int i, String mystring ){ } (can’t) D)public void Amethod(int i, String s) { } (can ) Liang, Introduction to Java Programming, revised by Dai-kaiyu Can can’t Can 31

Override vs Overload l Override ¡ Same method signature and return type ¡ Sub

Override vs Overload l Override ¡ Same method signature and return type ¡ Sub class can’t narrow the access right of the method comparing to super class ¡ Static method can’t be overridden as non-static ¡ Non-static method can’t be overridden as static ¡ Private method can’t be inherited , so can’t be overridden Liang, Introduction to Java Programming, revised by Dai-kaiyu 32

A Quiz which ones is correct public class Base { public void method() {…}

A Quiz which ones is correct public class Base { public void method() {…} public class Base { } public void method() {…} } public class Sub extends Base{ public class Sub extends Base { public int method() { public void method(){…} return 0; public int method(int a) { } return 0; } } } public class Base { public void method() {…} } public class Sub extends Base { private void method() {…} } Liang, Introduction to Java Programming, revised by Dai-kaiyu 33

Note about override l An instance method can be overridden only if it is

Note about override l 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. l If a method defined in a subclass is private in its superclass, the two methods are completely unrelated. Liang, Introduction to Java Programming, revised by Dai-kaiyu 34

NOTE l Like an instance method, a static method can be inherited. l. However,

NOTE l Like an instance method, a static method can be inherited. l. However, a static method cannot be overridden. l. If a static method defined in the superclass is redefined in a subclass, the method defined in the superclass is hidden. (more will be introduced later) Liang, Introduction to Java Programming, revised by Dai-kaiyu 35

Relationship between Superclass Objects and Subclass Objects l Subclass ¡ Can l object be

Relationship between Superclass Objects and Subclass Objects l Subclass ¡ Can l object be treated as superclass object Reverse is not true • Shape is not always a Circle ¡ Every class implicitly extends java. lang. Object Liang, Introduction to Java Programming, revised by Dai-kaiyu 36

The Object Class Every class in Java is descended from the java. lang. Object

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. Liang, Introduction to Java Programming, revised by Dai-kaiyu 37

The to. String() method in Object The to. String() method returns a string representation

The to. String() method in Object The to. String() 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. Cylinder my. Cylinder = new Cylinder(5. 0, 2. 0); System. out. println(my. Cylinder. to. String()); hashcode The code displays something like Cylinder@15037 e 5. This message is not very helpful or informative. Usually you should override the to. String method so that it returns a digestible string representation of the object. Liang, Introduction to Java Programming, revised by Dai-kaiyu 38

Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]

Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[] args) { m(new Graduate. Student()); m(new Person()); m(new Object()); } public static void m(Object x) { System. out. println(x. to. String()); } } class Graduate. Student extends Student { } class Student extends Person { public String to. String() { return "Student"; } } class Person extends Object { public String to. String() { 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. Which implementation of to. String is used will be determined dynamically by the Java Virtual Machine at runtime. This capability is known as dynamic binding. Liang, Introduction to Java Programming, revised by Dai-kaiyu 39

Dynamic Binding Dynamic binding works as follows: Suppose an object o is an instance

Dynamic Binding Dynamic binding works as follows: Suppose an object o is an instance of classes C 1, C 2, . . . , Cn-1, and Cn, where C 1 is a subclass of C 2, C 2 is a subclass of C 3, . . . , and Cn-1 is a subclass of Cn. That is, Cn is the most general class, and C 1 is the most specific class. In Java, Cn is the Object class. If o invokes a method p, the JVM searches the implementation for the method p in C 1, C 2, . . . , Cn-1 and Cn, in this order, until it is found. Once an implementation is found, the search stops and the first-found implementation is invoked. Liang, Introduction to Java Programming, revised by Dai-kaiyu 40

Method Matching vs. Binding l. Matching a method signature and binding a method implementation

Method Matching vs. Binding l. Matching a method signature and binding a method implementation are two issues. Static polymorphism 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. ¡ Dynamic polymorphism Demo Sub. java Liang, Introduction to Java Programming, revised by Dai-kaiyu 41

Generic Programming public class Test { public static void main(String[] args) { m(new Graduate.

Generic Programming public class Test { public static void main(String[] args) { m(new Graduate. Student()); m(new Person()); m(new Object()); } public static void m(Object x) { System. out. println(x. to. String ()); } } class Graduate. Student extends Student { } class Student extends Person { public String to. String() { return "Student"; } } class Person extends Object { public String to. String() { 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. , to. String) is determined dynamically. Liang, Introduction to Java Programming, revised by Dai-kaiyu 42

Casting Objects Casting can also be used to convert an object of one class

Casting Objects 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); upcasting The statement Object o = new Student(), known as implicit casting, is legal because an instance of Student is automatically an instance of Object. Liang, Introduction to Java Programming, revised by Dai-kaiyu 43

Why Casting Is Necessary? Suppose you want to assign the object reference o to

Why Casting Is Necessary? Suppose you want to assign the object reference o to a variable of the Student type using the following statement: l Student b = o; 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. l. To tell the compiler that o is a Student object, use an explicit casting. Enclose the target object type in parentheses and place it before the object to be cast, as follows: Student b = (Student)o; // Explicit casting Liang, Introduction to Java Programming, revised by Dai-kaiyu 44

Casting from Superclass to Subclass Explicit casting must be used when casting an object

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. Cylinder my. Cylinder = (Cylinder)my. Circle; Apple x = (Apple)fruit; Orange x = (Orange)fruit; downcasting Liang, Introduction to Java Programming, revised by Dai-kaiyu 45

The instanceof Operator Use the instanceof operator to test whether an object is an

The instanceof Operator Use the instanceof operator to test whether an object is an instance of a class: Circle my. Circle = new Circle(); if (my. Circle instanceof Cylinder) { Cylinder my. Cylinder = (Cylinder)my. Circle; . . . } Liang, Introduction to Java Programming, revised by Dai-kaiyu 46

1 // Point. java protected members prevent 2 // Definition of class Point 3

1 // Point. java protected members prevent 2 // Definition of class Point 3 clients from direct access (unless 4 public class Point { clients are Point subclasses or 5 protected int x, y; // coordinates of Point are in same package) 6 7 // No-argument constructor 8 public Point() 9 { 10 // implicit call to superclass constructor occurs here 11 set. Point( 0, 0 ); 12 } 13 14 // constructor 15 public Point( int x. Coordinate, int y. Coordinate ) 16 { 17 // implicit call to superclass constructor occurs here 18 set. Point( x. Coordinate, y. Coordinate ); 19 } 20 21 // set x and y coordinates of Point 22 public void set. Point( int x. Coordinate, int y. Coordinate ) 23 { 24 x = x. Coordinate; 25 y = y. Coordinate; 26 } 27 28 // get x coordinate 29 public int get. X() 30 { Liang, Introduction to Java Programming, revised 31 return x; by Dai-kaiyu 32 } 33 47

34 35 36 37 38 39 40 41 42 43 44 45 46 }

34 35 36 37 38 39 40 41 42 43 44 45 46 } // get y coordinate public int get. Y() { return y; } // convert into a String representation public String to. String() { return "[" + x + ", " + y + "]"; } // end class Point Liang, Introduction to Java Programming, revised by Dai-kaiyu 48

1 // Fig. 9. 5: Circle. java 2 // Definition of class Circle is

1 // Fig. 9. 5: Circle. java 2 // Definition of class Circle is a Point subclass 3 4 public class Circle extends Point { // inherits from Point 5 protected double radius; 6 Circle inherits Point’s 7 // no-argument constructor protected variables and public 8 public Circle() methods (except for constuctor) 9 { 10 // implicit call to superclass constructor occurs here 11 set. Radius( 0 ); 12 } Implicit call to Point constructor 13 14 // constructor 15 public Circle( double circle. Radius, int x. Coordinate, 16 int y. Coordinate ) Error occurs If no non 17 { arg constructor in 18 // call superclass constructor to set coordinates Point Class 19 super( x. Coordinate, y. Coordinate ); 20 Explicit call to Point 21 // set radius constructor using super 22 set. Radius( circle. Radius ); 23 } 24 25 // set radius of Circle 26 public void set. Radius( double circle. Radius ) 27 { 28 radius = ( circle. Radius >= 0. 0 ? circle. Radius : 0. 0 ); 29 } 30 Implicit call to Point constructor only apply to the non-arg constructor Liang, Introduction to Java Programming, revised by Dai-kaiyu 49

31 32 33 34 35 36 37 38 39 40 41 42 43 44

31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 } // get radius of Circle public double get. Radius() { return radius; } // calculate area of Circle public double area() { return Math. PI * radius; } // convert the Circle to a String public String to. String() { return "Center = " + "[" + x + ", " + y + "]" + "; Radius = " + radius; } Override method to. String of class Point by using same signature // end class Circle Liang, Introduction to Java Programming, revised by Dai-kaiyu 50

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 // Inheritance. Test. java // Demonstrating the "is a" relationship // Java core packages import java. text. Decimal. Format; // Java extension packages import javax. swing. JOption. Pane; public class Inheritance. Test { // test classes Point and Circle public static void main( String args[] ) { Point point 1, point 2; Circle circle 1, circle 2; Instantiate Point and Circle objects point 1 = new Point( 30, 50 ); circle 1 = new Circle( 2. 7, 120, 89 ); String output = "Point point 1: " + point 1. to. String() + "n. Circle circle 1: " + circle 1. to. String(); // use "is a" relationship to refer to a Circle // with a Point reference point 2 = circle 1; // assigns Circle to a Point reference output += "nn. Circle circle 1 (via point 2 reference): " + point 2. to. String(); Circle invokes its overridden to. String method Superclass object can reference subclass object Point still invokes Circle’s overridden to. String method // use downcasting (casting a superclass reference to a // subclass data type) to assign point 2 to circle 2 = ( Circle ) point 2; Liang, Introduction to Java Programming, revised by Dai-kaiyu Downcast Point to Circle 51

35 output += "nn. Circle circle 1 (via circle 2): " + Circle invokes

35 output += "nn. Circle circle 1 (via circle 2): " + Circle invokes its overridden 36 circle 2. to. String(); to. String method 37 38 Decimal. Format precision 2 = new Decimal. Format( "0. 00" ); 39 output += "n. Area of c (via circle 2): " + Circle invokes method area 40 precision 2. format( circle 2. area() ); 41 42 // attempt to refer to Point object with Circle reference 43 if ( point 1 instanceof Circle ) { 44 circle 2 = ( Circle ) point 1; Use instanceof to determine 45 output += "nncast successful"; if Point refers to Circle 46 } 47 else 48 output += "nnpoint 1 does not refer to a Circle"; 49 50 JOption. Pane. show. Message. Dialog( null, output, If Point refers to Circle, 51 "Demonstrating the "is a" relationship", cast Point as Circle 52 JOption. Pane. INFORMATION_MESSAGE ); 53 54 System. exit( 0 ); 55 } 56 57 } // end class Inheritance. Test Liang, Introduction to Java Programming, revised by Dai-kaiyu 52

Assigning subclass references to superclass references Liang, Introduction to Java Programming, revised by Dai-kaiyu

Assigning subclass references to superclass references Liang, Introduction to Java Programming, revised by Dai-kaiyu 53

Example 8. 1 Demonstrating Polymorphism and Casting This example creates two geometric objects: a

Example 8. 1 Demonstrating Polymorphism and Casting This example creates two geometric objects: a circle, and a cylinder, invokes the display. Geometric. Object method to display the objects. The display. Geometric. Object displays the area and perimeter if the object is a circle, and displays area and volume if the object is a cylinder. Test. Polymorphism. Casting Run Liang, Introduction to Java Programming, revised by Dai-kaiyu 54

Hiding Fields and Static Methods (Optional) l. You can override an instance method, but

Hiding Fields and Static Methods (Optional) l. You can override an instance method, but you cannot override a field (instance or static) or a static method. l. 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. l. 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. Liang, Introduction to Java Programming, revised by Dai-kaiyu 55

Hiding Fields and Static Methods, cont. l. When invoking an instance method from a

Hiding Fields and Static Methods, cont. l. 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. l. When accessing a field or a static method, the declared type of the reference variable decides which method is used at compilation time. Demo Sub. Static. java Liang, Introduction to Java Programming, revised by Dai-kaiyu 56

The protected Modifier l The protected modifier can be applied on data and methods

The protected Modifier l 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. l private, default, protected, public Liang, Introduction to Java Programming, revised by Dai-kaiyu 57

Accessibility Summary Liang, Introduction to Java Programming, revised by Dai-kaiyu 58

Accessibility Summary Liang, Introduction to Java Programming, revised by Dai-kaiyu 58

Visibility Modifiers Liang, Introduction to Java Programming, revised by Dai-kaiyu 59

Visibility Modifiers Liang, Introduction to Java Programming, revised by Dai-kaiyu 59

A Subclass Cannot Weaken the Accessibility la subclass cannot weaken the accessibility of a

A Subclass Cannot Weaken the Accessibility la subclass cannot weaken the accessibility of a method defined in the superclass. public class Base { public void method() {…} } public class Sub extends Base { private void method() {…} } If above is admitted, then…conflict(compile correct , but runtime error, private can’t be accessed) Base base=new Sub(); base. method(); Liang, Introduction to Java Programming, revised by Dai-kaiyu 60

The final Modifier The modifiers are used on classes and class members (data and

The final Modifier 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. l The final class cannot be extended: final class Math {. . . } l The final variable is a constant: final static double PI = 3. 14159; l The final method cannot be overridden by its subclasses. Liang, Introduction to Java Programming, revised by Dai-kaiyu 61

Optional The equals() and hash. Code() Methods in the Object Class l The equals()

Optional The equals() and hash. Code() Methods in the Object Class l The equals() method compares the contents of two objects. l The hash. Code() 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. Liang, Introduction to Java Programming, revised by Dai-kaiyu 62

The equals Method The equals() method compares the contents of two objects. The default

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; } Liang, Introduction to Java Programming, revised by Dai-kaiyu 63

NOTE: == vs. equals l. The == comparison operator is used for comparing two

NOTE: == vs. equals l. The == comparison operator is used for comparing two primitive data type values or for determining whether two objects have the same references. l. 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. l. The == operator is stronger than the equals method, in that the == operator checks whether the two reference variables refer to the same object. Liang, Introduction to Java Programming, revised by Dai-kaiyu 64

The hash. Code() method l. The hash. Code implemented in the Object class returns

The hash. Code() method l. The hash. Code implemented in the Object class returns the internal memory address of the object in hexadecimal. l. Your class should override the hash. Code method whenever the equals method is overridden. By contract, if two objects are equal, their hash codes must be same. Demo Test. Hashcode. java Liang, Introduction to Java Programming, revised by Dai-kaiyu 65

Optional The finalize, clone, and get. Class Methods l. The finalize method is invoked

Optional The finalize, clone, and get. Class Methods l. The finalize method is invoked by the garbage collector on an object when the object becomes garbage. l. The clone() method copies an object. l. The get. Class() 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. Demo frontend java. lang. Class. get. Name() Reflection Test. Hashcode. java Circle. java Liang, Introduction to Java Programming, revised by Dai-kaiyu 66

Finalizers l Garbage collection ¡ ¡ Returns memory to system Java performs this automatically

Finalizers l Garbage collection ¡ ¡ Returns memory to system Java performs this automatically l l object marked for garbage collection if no references to object Finalizer method ¡ ¡ Returns resources to system Java provides method finalize l l l Defined in java. lang. Object Receives no parameters Returns void Liang, Introduction to Java Programming, revised by Dai-kaiyu 67

1 // Employee. java 2 // Employee class definition. Employee objects share one 3

1 // Employee. java 2 // Employee class definition. Employee objects share one 3 public class Employee extends Object { 4 private String first. Name; instance of count 5 private String last. Name; 6 private static int count; // number of objects in memory 7 8 // initialize employee, add 1 to static count and 9 // output String indicating that constructor was called 10 public Employee( String first, String last ) 11 { 12 first. Name = first; 13 last. Name = last; 14 15 ++count; // increment static count of employees 16 System. out. println( "Employee object constructor: " + 17 first. Name + " " + last. Name ); Called when Employee 18 } for garbage collection 19 20 // subtract 1 from static count when garbage collector 21 // calls finalize to clean up object and output String 22 // indicating that finalize was called 23 protected void finalize() 24 { 25 --count; // decrement static count of employees 26 System. out. println( "Employee object finalizer: " + 27 first. Name + " " + last. Name + "; count = " + count ); 28 } 29 30 // get first name 31 public String get. First. Name() 32 { 33 return first. Name; Liang, Introduction to Java Programming, revised 34 } by Dai-kaiyu 35 is marked 68

36 37 38 39 40 41 42 43 44 45 46 47 48 }

36 37 38 39 40 41 42 43 44 45 46 47 48 } // get last name public String get. Last. Name() { return last. Name; } static method accesses static variable count // static method to get static count value public static int get. Count() { return count; } // end class Employee Liang, Introduction to Java Programming, revised by Dai-kaiyu 69

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // Employee. Test. java // Test Employee class with static class variable, // static class method, and dynamic memory. import javax. swing. *; Employee. Test public class Employee. Test { can invoke Employee static method, even though Employee has not been instantiated // test class Employee public static void main( String args[] ) { // prove that count is 0 before creating Employees String output = "Employees before instantiation: " + Employee. get. Count(); // create two Employees; count should be 2 Employee e 1 = new Employee( "Susan", "Baker" ); Employee e 2 = new Employee( "Bob", "Jones" ); // Prove that count is 2 after creating two Employees. // Note: static methods should be called only via the // class name for the class in which they are defined. output += "nn. Employees after instantiation: " + "nvia e 1. get. Count(): " + e 1. get. Count() + "nvia e 2. get. Count(): " + e 2. get. Count() + "nvia Employee. get. Count(): " + Employee. get. Count(); // get names of Employees output += "nn. Employee 1: " + e 1. get. First. Name() + " " + e 1. get. Last. Name() + "n. Employee 2: " + e 2. get. First. Name() + " " + e 2. get. Last. Name(); Liang, Introduction to Java Programming, revised by Dai-kaiyu 70

32 // If there is only one reference to each employee (as 33 //

32 // If there is only one reference to each employee (as 33 // on this example), the following statements mark 34 // those objects for garbage collection. Otherwise, 35 // these statement simply decrement the reference count 36 // for each object. 37 e 1 = null; Calls Java’s automatic garbage 38 e 2 = null; collection mechanism 39 40 System. gc(); // suggest call to garbage collector 41 42 // Show Employee count after calling garbage collector. 43 // Count displayed may be 0, 1 or 2 depending on 44 // whether garbage collector executed immediately and 45 // number of Employee objects it collects. 46 output += "nn. Employees after System. gc(): " + 47 Employee. get. Count(); 48 49 JOption. Pane. show. Message. Dialog( null, output, 50 "Static Members and Garbage Collection", 51 JOption. Pane. INFORMATION_MESSAGE ); 52 53 System. exit( 0 ); 54 } 55 56 } // end class Employee. Test Employee object constructor: Susan Baker constructor: Bob Jones finalizer: Susan Baker; count = 1 finalizer: Bob Jones; count = 0 Liang, Introduction to Java Programming, revised by Dai-kaiyu 71

Liang, Introduction to Java Programming, revised by Dai-kaiyu 72

Liang, Introduction to Java Programming, revised by Dai-kaiyu 72

Initialization Block Initialization blocks can be used to initialize objects along with the constructors.

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. Liang, Introduction to Java Programming, revised by Dai-kaiyu 73

Static Initialization Block l. A static initialization block is much like a nonstatic initialization

Static Initialization Block l. 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. l. The l JVM loads a class when it is needed. A superclass is loaded before its subclasses. Liang, Introduction to Java Programming, revised by Dai-kaiyu 74

Static Initialization Block lclass l l l l l} Sub. Static. Initial extends Super.

Static Initialization Block lclass l l l l l} Sub. Static. Initial extends Super. Static. Initial { static { System. out. println("sub's static initialization block " + "is invoked"); } lclass l l l} Super. Static. Initial { static { System. out. println("super's static initialization block " + "is invoked"); } public static void main(String args[]) { Sub. Static. Initial test = new Sub. Static. Initial(); } Demo Sub. Static. Initial. java Liang, Introduction to Java Programming, revised by Dai-kaiyu 75

Initialization Block l The order of excution ¡ When the class is used for

Initialization Block l The order of excution ¡ When the class is used for the first time. Load the class, (the superclass is loaded first) initialize static data fields, and excute the static initialization block of the class ¡ When the object is created, constructor is invoked Invoke the constructor of the superclass l Initialize instance data fields and execute instance initialization blocks l Execute the body of the constructor l See the example in the book. Liang, Introduction to Java Programming, revised by Dai-kaiyu 76