Transcript 08slide.ppt

Chapter 8 Inheritance and Polymorphism

Prerequisites for Part II

Chapter 5 Arrays Chapter 6 Objects and Classes Chapter 7 Strings Chapter 8 Inheritance and Polymorphism Chapter 9 Abstract Classes and Interfaces Chapter 10 Object-Oriented Modeling You can cover GUI after Chapter 8 Chapter 11 Getting Started with GUI Programming Chapter 12 Event-Driven Programming Chapter 15 Exceptions and Assertions Chapter 16 Simple Input and Output Liang,Introduction to Java Programming,revised by Dai-kaiyu 一切皆有缘起 You can cover Exceptions and I/O after Chapter 8 1

Objectives

          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), hashCode(), toString(), finalize(), clone(), and getClass()) 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).

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

Introduction

Object-oriented programming

Inheritance

 Software reusability  Classes are created from existing ones • Absorbing attributes and behaviors • Adding new capabilities 

Polymorphism

 Enables developers to write programs in general fashion  Helps add new capabilities to system 3 Liang,Introduction to Java Programming,revised by Dai-kaiyu

Introduction (cont.)

Object-oriented programming

 Inheritance 

Subclass

• inherits from

superclass

Subclass usually adds instance variables and methods  Single vs. multiple inheritance •

Java does not support multiple inheritance

Interfaces (discussed later) achieve the same effect

“Is a”

relationship 

Composition

“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 to Java Programming,revised by Dai-kaiyu 5

Superclasses and Subclasses

 “

Is a” Relationship

 Object “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

Circle Superclass Circle Methods Circle Data Inheritance Subclass Cylinder Circle Methods Cylinder Methods Circle Data Cylinder Data Superclass Subclass

UML Diagram

Circle -r adius +getRadius +setRadius +findArea Liang,Introduction to Java Programming,revised by Dai-kaiyu Cylinder -length +getLength +setLength +findVolume 7

// Cylinder.java: Class definition for describing Cylinder public class Cylinder extends Circle { private double length = 1;

Superclass supertype

/** Return length */ public double getLength() {

Circle -r adius

return length; }

+getRadius +setRadius +findArea

/** Set length */ public void setLength(double length) { this.length = length; } } /** Return the volume of this cylinder */ public double findVolume() { return findArea() * length; }

Liang,Introduction to Java Programming,revised by Dai-kaiyu subtype Subclass Cylinder -length +getLength +setLength +findVolume 8

Cylinder cylinder = new Cylinder(); System.out.println("The length is " + cylinder.getLength()); System.out.println("The radius is " + cylinder.getRadius()); System.out.println("The volume of the cylinder is " + cylinder.findVolume()); System.out.println("The area of the circle is " + cylinder.findArea()); The output is

Pravate data fields and mothods will not be inherited in a subclass

The length is 1.0

The radius is 1.0

The volume of the cylinder is 3.14159

The area of the circle is 3.14159

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

An inheritance hierarchy for university

CommunityMembers

.

CommunityMember

superclass

is a

direct

of

Employee CommunityMember

is an

indirect superclass

Faculty

of

CommunityMember Employee Student Alumni Faculty Administrator Teacher Staff

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

A portion of a

Shape

class hierarchy.

Shape TwoDimensionalShape Circle Square Triangle ThreeDimensionalShape Sphere Cube Tetrahedron

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

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:

 To call a superclass constructor  To call a superclass method Liang,Introduction to Java Programming,revised by Dai-kaiyu 12

CAUTION

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

.

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

NOTE

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

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. If none of them is invoked explicitly, the compiler puts

super( )

as the first statement in the constructor

. For example, public Cylinder() { } public A(double d) { // some statements } is equivalent to is equivalent to public Cylinder() { super(); } public A(double d) { super(); // some statements } Liang,Introduction to Java Programming,revised by Dai-kaiyu 15

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 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) { 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) { 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) { new Faculty(); } } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } 3. Invoke Employee’s no class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); arg 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) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } } 4. Invoke Employee(String) class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); 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) { 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) { 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) { 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) { 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) { 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 no arg 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

Declaring a Subclass

A subclass extends properties and methods from the superclass. You can also:

 Add new properties  Add new methods  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 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 findArea() // 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 findArea() { return 2 * super.findArea() + 2 * getRadius() * Math.PI * length; } } // Other methods are omitted

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

Override vs Overload

Overload:

same name

different signature (by parameters)

Can have different return type

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

Can can’t can’t Can

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

Override vs Overload

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

A Quiz

which ones is correct

public class Base { public void method() {…} } public class Sub extends Base{ public int method() { } } return 0; public class Base { public void method() {…} } public class Sub extends Base { public void method(){…} 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

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

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

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. (more will be introduced later) 35 Liang,Introduction to Java Programming,revised by Dai-kaiyu

Relationship between Superclass Objects and Subclass Objects

Subclass object

 Can 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 class. If no inheritance is specified when a class is defined, the superclass of the class is Object.

public class Circle { ... } Equivalent public class Circle extends Object { ... } 37 Liang,Introduction to Java Programming,revised by Dai-kaiyu

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 (@), and

a number

representing this object.

at

sign Cylinder myCylinder = new Cylinder(5.0, 2.0); System.out.println(myCylinder.toString()); hashcode The code displays something like Cylinder@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.

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

Polymorphism, Dynamic Binding and Generic Programming

public class Test { 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 capability is known as polymorphism will be determined dynamically by the Java Virtual Machine at runtime. This dynamic binding .

.

Which implementation of toString is used

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

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 of C 2 is, C n , C 2 is a subclass of C 3 , ..., and C n-1 is the most general class, and C 1 In Java, C n is a subclass is a subclass of C n . That is the most specific class. 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.

C n C n-1 . . . . . C 2 C 1 Object Since o is an instance of C 1 , o is also an instance of C 2, C 3, …, C n-1 , and C n 40 Liang,Introduction to Java Programming,revised by Dai-kaiyu

Method Matching vs. Binding

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

.

Demo Sub.java

Dynamic polymorphism

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

Generic Programming

public class Test { 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 Student or String).

.

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

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

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 a variable of the Student type using the following statement: 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.

 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 from a superclass to a subclass.

of casting may not always succeed.

This type

Cylinder myCylinder = (Cylinder)myCircle; Apple x = (Apple)fruit; Orange x = (Orange)fruit; downcasting 45 Liang,Introduction to Java Programming,revised by Dai-kaiyu

The

instanceof

Operator

Use the

instanceof

operator to test whether an object is an instance of a class:

Circle myCircle = new Circle(); if (myCircle instanceof Cylinder) { Cylinder myCylinder = (Cylinder)myCircle; } ...

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

1 // Point.java

2 // Definition of class Point 3 4 public class Point { 5 protected int x, y; // coordinates of Point 6 7 // No-argument constructor 8 public Point() 9 { protected

clients are

10 // implicit call to superclass constructor occurs here 11 setPoint( 0, 0 ); 12 } 13 14 // constructor 15 public Point( int xCoordinate, int yCoordinate ) 16 {

members prevent clients from direct access (unless

Point

subclasses or are in same package)

17 // implicit call to superclass constructor occurs here 18 setPoint( xCoordinate, yCoordinate ); 19 } 20 21 // set x and y coordinates of Point 22 public void setPoint( int xCoordinate, int yCoordinate ) 23 { 24 x = xCoordinate; 25 y = yCoordinate; 26 } 27 28 // get x coordinate 29 public int getX() 30 { 31 return x; 32 } 33

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

34 // get y coordinate 35 public int getY() 36 { 37 return y; 38 } 39 40 // convert into a String representation 41 public String toString() 42 { 43 return "[" + x + ", " + y + "]"; 44 } 45 46 } // end class Point

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

1 // Fig. 9.5: Circle.java

2 // Definition of class Circle Circle 3 4 public class Circle extends Point { // inherits from Point

is a

Point

subclass

5 protected double radius; 6 7 // no-argument constructor Circle protected

inherits

Point

’s variables and

public 8 public Circle() 9 { 12 }

methods (except for constuctor)

10 // implicit call to superclass constructor occurs here 11 setRadius( 0 ); 13 14 // constructor

Implicit call to

Point

constructor

15 public Circle( double circleRadius, int xCoordinate, 16 int yCoordinate ) 17 { 18 // call superclass constructor to set coordinates 19 super( xCoordinate, yCoordinate ); 20 21 // set radius 22 setRadius( circleRadius ); 23 } 24

Explicit call to

Point

constructor using

super 25 // set radius of Circle 26 public void setRadius( double circleRadius )

Error occurs If no non arg constructor in Point Class

27 { 28 radius = ( circleRadius >= 0.0 ? circleRadius : 0.0 ); 29 } 30

Implicit call to

Point

constructor only apply to by Dai-kaiyu 49

31 // get radius of Circle 32 public double getRadius() 33 { 34 return radius; 35 } 36 37 // calculate area of Circle 38 public double area() 39 { 40 return Math.PI * radius * radius; 41 } 42 43 // convert the Circle to a String 44 public String toString() 45 { 46 return "Center = " + "[" + x + ", " + y + "]" + 47 "; Radius = " + radius; 48 } 49 50 } // end class Circle

Override

Point

method

toString

of class by using same signature Liang,Introduction to Java Programming,revised by Dai-kaiyu 50

1 // InheritanceTest.java

2 // Demonstrating the "is a" relationship 3 4 // Java core packages 5 import java.text.DecimalFormat; 6 7 // Java extension packages 8 import javax.swing.JOptionPane; 9 10 public class InheritanceTest { 11 12 // test classes Point and Circle 13 public static void main( String args[] )

Instantiate

Point

and

Circle

objects

14 { 15 Point point1, point2; 16 Circle circle1, circle2; 17 18 point1 = new Point( 30, 50 ); 19 circle1 = new Circle( 2.7, 120, 89 ); 20 21 String output = "Point point1: " + point1.toString() + 22 "\nCircle circle1: " + circle1.toString(); 23 24 // use "is a" relationship to refer to a Circle 25 // with a Point reference 26 point2 = circle1; // assigns Circle to a Point reference 27 28 output += "\n\nCircle circle1 (via point2 reference): " + 29 point2.toString(); 30 31 // use downcasting (casting a superclass reference to a 32 // subclass data type) to assign point2 to circle2 33 circle2 = ( Circle ) point2; 34 Circle

invokes its overridden

toString

method Superclass object can reference subclass object

Point

still invokes overridden Liang,Introduction to Java Programming,revised Downcast

Circle toString

method

Point

’s to

Circle

51 by Dai-kaiyu

35 output += "\n\nCircle circle1 (via circle2): " + 36 circle2.toString(); 37 38 DecimalFormat precision2 = new DecimalFormat( "0.00" ); 39 output += "\nArea of c (via circle2): " + 40 precision2.format( circle2.area() ); 41 42 // attempt to refer to Point object with Circle reference 43 if ( point1 instanceof Circle ) { 44 circle2 = ( Circle ) point1; 45 output += "\n\ncast successful"; 46 } 47 else Circle

invokes its overridden

toString

method

Circle

invokes method

area Use instanceof to determine if Point refers to Circle 48 output += "\n\npoint1 does not refer to a Circle"; 49 50 JOptionPane.showMessageDialog( null, output, 51 "Demonstrating the \"is a\" relationship", 52 JOptionPane.INFORMATION_MESSAGE ); 53 54 System.exit( 0 ); 55 } 56 57 } // end class InheritanceTest

If

Point

cast refers to

Point

as

Circle Circle

, 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 53

Example 8.1

Demonstrating Polymorphism and Casting

This example creates two geometric objects: a circle, and a cylinder, invokes the displayGeometricObject method to display the objects. The displayGeometricObject displays the area and perimeter if the object is a circle, and displays area and volume if the object is a cylinder.

TestPolymorphismCasting Run Liang,Introduction to Java Programming,revised by Dai-kaiyu 54

Hiding Fields and Static Methods (Optional)

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

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

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.

Demo SubStatic.java

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

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.

private, default, protected, public

Visibility increases private, none (if no modifier is used), protected, public 57 Liang,Introduction to Java Programming,revised by Dai-kaiyu

Accessibility Summary

Modifier on members in a class public Accessed from the same class protected Accessed from the same package Accessed from a subclass default private Accessed from a different package Liang,Introduction to Java Programming,revised by Dai-kaiyu 58

Visibility Modifiers

package p1; public class C1 { public int x; protected int y; int z; private int u; protected void m() { } } public class C3 extends C1 { can access x; can access y; can access z; cannot access u; can invoke m(); } public class C2 { C1 o = new C1(); can access o.x; can access o.y; can access o.z; cannot access o.u; can invoke o.m(); } package p2; public class C4 extends C1 { can access x; can access y; cannot access z; cannot access u; can invoke m(); } Liang,Introduction to Java Programming,revised by Dai-kaiyu public class C5 { C1 o = new C1(); can access o.x; cannot access o.y; cannot access o.z; cannot access o.u; cannot invoke o.m(); } 59

A Subclass Cannot Weaken the Accessibility

a 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 methods), except that the

final modifier can also be used on local variables in a method

.

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.

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

Optional

The equals() and hashCode() Methods in the Object Class

The

equals()

method compares the contents of two objects.

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.

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

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; }

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

NOTE: == vs. equals

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

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

The hashCode() method

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

.

Demo TestHashcode.java

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

Optional

The finalize, clone, and getClass Methods

 The

finalize

method is invoked by the garbage collector on an object when the object becomes garbage.  The

clone()

method copies an object.

 The

getClass()

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

java.lang.Class.getName()

Reflection

Demo frontend TestHashcode.java

Circle.java

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

Finalizers

 Garbage collection  Returns memory to system  Java performs this automatically  object marked for garbage collection if no references to object  Finalizer method  Returns resources to system  Java provides method

finalize

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

3 public class Employee extends Object { 4 private String firstName; 5 private String lastName; 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 )

Employee objects share one instance of count

11 { 12 firstName = first; 13 lastName = last; 14 15 ++count; // increment static count of employees 16 System.out.println( "Employee object constructor: " + 17 firstName + " " + lastName ); 18 } 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 firstName + " " + lastName + "; count = " + count ); 28 } 29 30 // get first name 31 public String getFirstName() 32 { 33 return firstName; 34 } 35

Called when Employee is marked for garbage collection Liang,Introduction to Java Programming,revised by Dai-kaiyu 68

36 // get last name 37 public String getLastName() 38 { 39 return lastName; 40 } 41 42 // static method to get static count value 43 public static int getCount() 44 { 45 return count; 46 } 47 48 } // end class Employee

static method accesses static variable count Liang,Introduction to Java Programming,revised by Dai-kaiyu 69

1 // EmployeeTest.java

2 // Test Employee class with static class variable, 3 // static class method, and dynamic memory.

4 import javax.swing.*; 5

EmployeeTest can invoke Employee static method, even though Employee has not

6 public class EmployeeTest { 7

been instantiated

8 // test class Employee 9 public static void main( String args[] ) 10 { 11 // prove that count is 0 before creating Employees 12 String output = "Employees before instantiation: " + 13 Employee.getCount(); 14 15 // create two Employees; count should be 2 16 Employee e1 = new Employee( "Susan", "Baker" ); 17 Employee e2 = new Employee( "Bob", "Jones" ); 18 19 // Prove that count is 2 after creating two Employees.

20 // Note: static methods should be called only via the 21 // class name for the class in which they are defined.

22 output += "\n\nEmployees after instantiation: " + 23 "\nvia e1.getCount(): " + e1.getCount() + 24 "\nvia e2.getCount(): " + e2.getCount() + 25 "\nvia Employee.getCount(): " + Employee.getCount(); 26 27 // get names of Employees 28 output += "\n\nEmployee 1: " + e1.getFirstName() + 29 " " + e1.getLastName() + "\nEmployee 2: " + 30 e2.getFirstName() + " " + e2.getLastName(); 31

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

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 e1 = null; 38 e2 = null;

Calls Java’s automatic garbage-

39 40 System.gc(); // suggest call to garbage collector

collection mechanism

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 += "\n\nEmployees after System.gc(): " + 47 Employee.getCount(); 48 49 JOptionPane.showMessageDialog( null, output, 50 "Static Members and Garbage Collection", 51 JOptionPane.INFORMATION_MESSAGE ); 52 53 System.exit( 0 ); 54 } 55 56 } // end class EmployeeTest Employee object constructor: Susan Baker Employee object constructor: Bob Jones Employee object finalizer: Susan Baker; count = 1 Employee object 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

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.

public class Book { private static int numOfObjects; private String title private int id; public Book(String title) { this.title = title; } public Book(int id) { this.id = id; }

{ numOfObjects++; }

} Equivalent public class Book { private static int numOfObjects; private String title; private int id; public Book(String title) {

numOfObjects++;

this.title = title; } public Book(int id) {

numOfObjects++;

this.id = id; } } Liang,Introduction to Java Programming,revised by Dai-kaiyu 73

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.

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

Static Initialization Block

class SubStaticInitial extends SuperStaticInitial {

static {

System.out.println("sub's static initialization block " +

"is invoked");

  

} public static void main(String args[])

 

{ SubStaticInitial test = new SubStaticInitial();

 

} }

class SuperStaticInitial {

static {

System.out.println("super's static initialization block " +

   

} } "is invoked"); Demo SubStaticInitial.java

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

Initialization Block

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  Initialize instance data fields and execute instance initialization blocks  Execute the body of the constructor See the example in the book.

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