Presentation is loading. Please wait.

Presentation is loading. Please wait.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 COS240 O-O Languages AUBG,

Similar presentations


Presentation on theme: "Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 COS240 O-O Languages AUBG,"— Presentation transcript:

1 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 COS240 O-O Languages AUBG, COS dept Lecture 14 Title: Polymorphism & Dynamic Binding in Java Reference: COS240 Syllabus

2 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 2 Lecture Contents: F To discover polymorphism. F To discover dynamic binding. F To describe casting and explain why explicit downcasting is necessary.  To restrict access to data and methods to subclasses only, using the protected visibility modifier.  To prevent class extending and method overriding using the final modifier

3 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 3 Motivations F It is a challenge from one side but gives power and flexibility if you are able to perform different tasks using the same calling statement. What is the way to achieve that effect? The answer is to apply POLYMORPHISM. F How to interpret the term POLYMORPHISM? F Polymorphism (from Greek meaning “many forms” )= F = Giving different meaning to the same thing F = Variable of a super type can refer to a subtype object –In assignment statement or –Through parameter passing mechanism

4 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 4 Sub type and Super type F A class defines a type.  A type defined by a subclass is a subtype.  A type defined by its superclass is a supertype. F For example: F Circle is a subtype of GeometricObject F GeometricObject is a supertype for Circle.

5 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 5 Polymorphism F Inheritance is a relation that enables a sub class to inherit features from its superclass with additional new features. F A subclass is a specialized form of its superclass. F Every instance of a sub class is an instance of a superclass BUT not vice versa. F Example: Every circle is a geometric object, BUT not every geometric object is a circle. F !!! You can always assign an instance of a subclass to a reference variable of its superclass type. F !!! You can always pass an actual argument /instance of a subclass type/ to meet corresponding formal parameter /instance of its superclass type/.

6 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 6 Consider code in Java // source text file: ProgBaseDerv1Derv2.java given inheritance hierarchy Object | Base / \ Derived1 Derived2 Classes Base, Derived1, Derived2 provide method toString() and method show()

7 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 7 Consider code in Java class Base { public void show() { System.out.println("Base " );} public String toString() { return "\n\nBase"; } } // end of class Base class Derived1 extends Base { public void show() { System.out.println("Derived1" );} public String toString() { return "\n\nDerived1"; } } // end of class Derived1 class Derived2 extends Base { public void show() { System.out.println("Derived2" );} public String toString() { return "\n\nDerived2"; } } // end of class Derived2

8 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 8 Consider code in Java // source text file: ProgBaseDerv1Derv2.java public class ProgBaseDerv1Derv2 { public static void main(String[] args) { Object o = new Object(); System.out.println(" " + o.toString()); Base a = new Base(); System.out.println(" " + a.toString()); a.show(); Derived1 b = new Derived1(), cir1 = new Derived1(); System.out.println(" " + b.toString()); b.show(); Derived2 c = new Derived2(), rect1 = new Derived2(); System.out.println(" " + c.toString()); c.show(); Object[ ] arr = new Object[4]; arr[0] = o; arr[1] = a; arr[2] = b; arr[3] = c; for(int i=0; i<4; i++) System.out.println( arr[i].toString()); // o is named polymorphic variable o=a; o=b; o=c; a=b; a=c; } // end of method main() } // end of class ProgBaseDerv1Derv2

9 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 9 Comments  Ref variable o is Object type.  Array ref variable arr is Object type.  We can assign any instance of Object ((eg. New Base, new Derived1, or new Derived2 to o or to arr array element F GEN RULE: An object of a subtype can be used wherever its supertype value is required or in other words a ref var of a super class type can point to an object of its sub class type. F This feature is known as polymorphism.

10 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 10 Consider code in Java // source text file: ProgPolymorphismDemo.java given inheritance hierarchy Object | GeometricObject / \ Circle Rectangle

11 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 11 Consider code in Java // source text file: ProgpolymorphismDemo.java public static void main(String args[]) { displayObject(new Circle(1, "red", false)); displayObject(new Rectangle(1, 1, "blue", true)); Circle aa = new Circle(1, "red", false); displayObject(aa); Rectangle bb = new Rectangle(1, 1, "blue", true); displayObject(bb); } // end of main public static void displayObject( GeometricObject o) { System.out.println("Created:"+o.getDateCreated()+" color:"+o.getColor()+" Filled:"+o.isFilled()); // or System.out.println("Created:"+o.dateCreated+" color:"+o.color+" Filled:"+o.filled); }

12 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 12 Comments  The formal param is GeometricObject o. F The actual argument may be any instance of GeometricObject (eg. New Circle or new Rectangle) F GEN RULE: An object of a subtype can be used wherever its supertype value is required or in other words a ref var of a super class type (formal param) can point to an object of its sub class type (actual arg). F This feature is known as polymorphism.

13 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 13 Dynamic Binding // file: ProgGeometricObject3.java Object o = new GeometricObject(); System.out.println(o.toString()); Object aa = new Circle(1); System.out.println(aa.toString()); Q. Which toString() method is invoked by o and by aa ? Before answer, let introduce two terms: declared type actual type

14 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 14 Dynamic Binding Object o = new GeometricObject(); A variable must be declared a type. The type of a variable is called its declared type. o’s declared type is Object. The actual type is the actual class for the object referenced by the variable o’s actual type is GeometricObject Which toString() method is invoked by o is determined by o’s actual type. This is known as dynamic binding

15 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 15 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.

16 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 16 class Person extends Object { public String toString() { return "Person"; } class Student extends Person { public String toString() { return "Student"; } class GraduateStudent extends Student { } 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()); } Program output is: Can you analyze? What is the expected result?

17 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 17 class Person extends Object { public String toString() { return "Person"; } class Student extends Person { public String toString() { return "Student"; } class GraduateStudent extends Student { } 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()); } Program output is: Student Person Java.lang.Object@16f0472

18 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 18 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.

19 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 19 Polymorphism and Dynamic Binding, 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.

20 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 20 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.

21 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 21 Method Matching vs. Binding Matching a method signature and binding a method implementation are two separate issues. The compiler finds a matching method according to parameter type, number of parameters, and order of the parameters at compile time (early, static binding). A method may be implemented in several subclasses. The Java Virtual Machine dynamically binds the implementation of the method at run time, decided by the actual type of the variable (late, dynamic binding).

22 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 22 Casting Objects You have already used the casting operator to convert variables of one primitive type to another. double d1=3.156, d2;int a1, a2=55; // casting – convert from int to double d2 = a2; // allowed d2 = (double) a2; // allowed // casting – convert from double to int a1 = d1; // compiler error a1 = (int) d1; // allowed Same approach applied when casting objects

23 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 23 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 formal 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.

24 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 24 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

25 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 25 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.

26 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 26 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; // explicit casting only allow Orange x = (Orange)fruit; Apple x = fruit; // implicit casting not allowed

27 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 27 Casting from Subclass to Superclass Explicit or implicit casting must be used when casting an object from a subclass to a superclass. This type of casting may always succeed. Fruit f1, f2; Apple apl = new Apple(); f1 = apl;// implicit casting allowed f2 = (Fruit)apl;// explicit casting allowed

28 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 28 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. Object o = new GeometricObject(); Circle ac = new Circle(); ac = o; // syntax error, not every geometric object is necessarily a circle. ac = (Circle) o; // OK, but casting may not always succeed

29 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 29 Casting from Subclass to Superclass Explicit or implicit casting must be used when casting an object from a subclass to a superclass. This type of casting may always succeed. Object o = new GeometricObject(); Circle ac = new Circle(); o=ac; o = (GeometricObject)ac; o = (Circle)ac;

30 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 30 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());... }

31 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 31 Example (8e): Demonstrating Polymorphism and Casting // source text file: ProgCastingDemo.java Given: inheritance relation Object - GeometricObject – Circle,Rectangle geometricObject (base class) – Circle, Rectangle (sub classes) Problem: write a program that creates two Object instances initialized as Circle(1.0) object and as a Rectangle(1.,1.0) object, and invokes the displayObject() method to display the objects. The displayObject() displays the area and diameter if the object is a circle, and displays area if the object is a rectangle.

32 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 32 Example (8e): Demonstrating Polymorphism and Casting F Examine the source text: F Q. which is the declared type and which is the actual type of o1 and o2? Object o1 = new Circle(1, "red", false); Object o2 = new Rectangle(1, 1, "blue", true);

33 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 33 Example (8e): Demonstrating Polymorphism and Casting F Examine the source text: F Q. what output is to display after following stmts? System.out.println(" "+ (o1 instanceof Object ) ); System.out.println(" "+ (o1 instanceof GeometricObject) ); System.out.println(" "+ (o1 instanceof Circle ) ); System.out.println(" "+ (o1 instanceof Rectangle ) );

34 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 34 Example (8e): Demonstrating Polymorphism and Casting F Examine the source text: F Q. what output is to display after following stmts? System.out.println(" "+ (o2 instanceof Object ) ); System.out.println(" "+ (o2 instanceof GeometricObject) ); System.out.println(" "+ (o2 instanceof Circle ) ); System.out.println(" "+ (o2 instanceof Rectangle ) );

35 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 35 Example (8e): Demonstrating Polymorphism and Casting F Examine the source text: F A. what output is to display after following stmts? o1 o2 Object true true GeometricObject true true Circle true false Rectangle false true

36 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 36 Example (5e): Demonstrating Polymorphism and Casting // source text file: ProgCastingDemo2.java Given: inheritance relation between circle – cylinder Circle (base class) – Cylinder (sub class) Problem: write a program that creates two objects, a circle and a cylinder, and invokes the displayObject() method to display them. The displayObject() method displays area if the object is circle and volume if the object is cylinder.

37 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 37 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; }

38 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 38 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.

39 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 39 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

40 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 40 Accessibility Summary

41 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 41 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.

42 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 42 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.

43 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 013213080743 Thank You for Your attention!


Download ppt "Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 COS240 O-O Languages AUBG,"

Similar presentations


Ads by Google