Download COS240Lec14_JAVAPolymorphism

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
COS240 O-O Languages
AUBG, COS dept
Lecture 14
Title:
Polymorphism
&
Dynamic Binding in Java
Reference: COS240 Syllabus
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
1
Lecture Contents:
To discover polymorphism.
 To discover dynamic binding.
 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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
2
Motivations
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.
How
to interpret the term POLYMORPHISM?
Polymorphism
(from Greek meaning “many forms” )=
= Giving different meaning to the same thing
= Variable of a super type can refer to a subtype object
– In assignment statement or
– Through parameter passing mechanism
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
3
Sub type and Super type
 A class
defines a type.
 A type defined by a subclass is a subtype.
 A type defined by its superclass is a supertype.
 For example:
 Circle is a subtype of GeometricObject
 GeometricObject is a supertype for Circle.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
4
Polymorphism
Inheritance is a relation that enables a sub class to
inherit features from its superclass with additional new
features.
 A subclass is a specialized form of its superclass.
 Every instance of a sub class is an instance of a
superclass BUT not vice versa.
 Example: Every circle is a geometric object, BUT not
every geometric object is a circle.
 !!! You can always assign an instance of a subclass to a
reference variable of its superclass type.
 !!! You can always pass an actual argument /instance of
a subclass type/ to meet corresponding formal
parameter /instance of its superclass type/.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
5
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()
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
6
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
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
7
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("
Base a = new Base();
a.show();
System.out.println("
" + o.toString());
" + a.toString());
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()
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
} // end of class
ProgBaseDerv1Derv2
rights reserved. 0132130807
8
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
 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.
 This feature is known as polymorphism.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
9
Consider code in Java
// source text file: ProgPolymorphismDemo.java
given inheritance hierarchy
Object
|
GeometricObject
/
\
Circle
Rectangle
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
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);
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
11
Comments

The formal param is GeometricObject o.
The actual argument may be any instance of
GeometricObject (eg. New Circle or new Rectangle)
 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).
 This feature is known as polymorphism.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
12
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
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
13
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
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
14
Dynamic Binding
Dynamic binding works as follows: Suppose an object o is an
instance of classes C1, C2, ..., Cn-1, and Cn, where C1 is a subclass
of C2, C2 is a subclass of C3, ..., and Cn-1 is a subclass of Cn. That
is, Cn is the most general class, and C1 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 C1, C2, ..., 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.
Cn
Cn-1
.....
C2
C1
Since o is an instance of C1, o is also an
Object
instance of C2, C3, …, Cn-1, and Cn
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
15
class Person extends Object {
public String toString() {
return "Person";
}
}
class Student extends Person {
public String toString() {
return "Student";
}
}
class GraduateStudent extends Student {
}
Program output is:
Can you analyze?
What is the expected result?
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());
}
}
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 {
}
Program output is:
Student
Student
Person
Java.lang.Object@16f0472
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());
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
17
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());
}
}
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.
class GraduateStudent extends Student {
}
class Student extends Person {
public String toString() {
return "Student";
}
}
class Person extends Object {
public String toString() {
return "Person";
}
}
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
18
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
19
Dynamic Binding
Dynamic binding works as follows: Suppose an object o is an
instance of classes C1, C2, ..., Cn-1, and Cn, where C1 is a subclass
of C2, C2 is a subclass of C3, ..., and Cn-1 is a subclass of Cn. That
is, Cn is the most general class, and C1 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 C1, C2, ..., 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.
Cn
Cn-1
.....
C2
C1
Since o is an instance of C1, o is also an
Object
instance of C2, C3, …, Cn-1, and Cn
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
20
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).
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
21
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
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
22
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
23
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
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
24
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
25
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
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
26
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
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
27
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
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
28
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;
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
29
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());
...
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
30
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
31
Example (8e): Demonstrating
Polymorphism and Casting
 Examine
the source text:
 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);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
32
Example (8e): Demonstrating
Polymorphism and Casting
Examine the source text:
 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 ) );
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
33
Example (8e): Demonstrating
Polymorphism and Casting
Examine the source text:
 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 ) );
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
34
Example (8e): Demonstrating
Polymorphism and Casting
Examine the source text:
 A. what output is to display after following stmts?

Object
GeometricObject
Circle
Rectangle
o1
true
true
true
false
o2
true
true
false
true
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
35
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
36
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, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
37
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
38
The protected Modifier
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.
 The
 private,
default, protected, public
Visibility increases
private, none (if no modifier is used), protected, public
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
39
Accessibility Summary
Modifier
on members
in a class
Accessed
from the
same class
Accessed
from the
same package
Accessed
from a
subclass
Accessed
from a different
package
public
-
protected
default
private
-
-
-
-
-
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
40
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
41
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
42
Thank You
for
Your attention!
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
43