0% found this document useful (0 votes)
23 views27 pages

8 Polymorphism

Chapter 11 discusses inheritance and polymorphism in Java, focusing on concepts such as isA relationships, implicit and explicit casting, and the use of the instanceof operator. It explains dynamic binding, method matching, and the importance of the @Override annotation for improving code readability. Additionally, it covers access modifiers, the ArrayList class, and the rules regarding subclass accessibility and method overriding.

Uploaded by

shamim.241
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views27 pages

8 Polymorphism

Chapter 11 discusses inheritance and polymorphism in Java, focusing on concepts such as isA relationships, implicit and explicit casting, and the use of the instanceof operator. It explains dynamic binding, method matching, and the importance of the @Override annotation for improving code readability. Additionally, it covers access modifiers, the ArrayList class, and the rules regarding subclass accessibility and method overriding.

Uploaded by

shamim.241
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 27

Chapter 11

Inheritance and
Polymorphism
(Continued)

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
isA relationships
Circle c = new Circle();
Object GeometricObject c = new Circle(); // Rectangle
Object c = new Circle(); // Rectangle

f(Object c){ f(c)


GeometricObject f(new Circle())
} f(new GeometricObject())
f(new Rectangle())

Circle Rectangle

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Implicit casting:
GeometricObject o = new Circle();

Explicit casting:
Circle c = (Circle) o;

c.radius c.getArea()
((Circle) o).radius ((Circle) o).getArea()

(Rectangle) o.radius (Rectangle) o.getArea()


ClassCastException

if (o instanceof Circle)
{
((Circle) o).radius;
((Circle) o).getArea();

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
display (Object o)
{
From driver class/main:
if (o instanceof Circle)
{ display (new Circle());
((Circle) o).radius; display (new Rectangle());
((Circle) o).getArea();

else if (o instanceof Rectangle)


{
((Rectangle) o).height;
((Rectangle) o).getArea();

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
@Override annotation

• a best practice for coding


in java
• If programmer makes any
mistake such as wrong
method name, wrong
parameter types while
overriding, you would get
a compile time error. As
by using this annotation
you instruct compiler that
you are overriding this
method.
• It improves the readability
of the code.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Note

• A type defined by subclass is subtype and a type


defined by superclass is supertype.

• You can pass an instance of a subclass to a


parameter of its superclass type

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

• The actual type of the variable is the actual class for the
object referenced by the ariable. Here o’s actual type is
GeometricObject, since o references to an object
created using new GeometricObject().

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
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
Method Matching vs. Binding
Matching a method signature and binding a method
implementation are two issues.

The compiler finds a matching method according to


parameter type, number of parameters, and order of the
parameters at compilation time.

A method may be implemented in several subclasses. The


Java Virtual Machine dynamically binds the
implementation of the method at runtime.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Generic programming
public class PolymorphismDemo {
public static void main(String[] args)
{ • Polymorphism allows methods to be
m(new GraduateStudent()); used generically for a wide range of
m(new Student());
m(new Person()); object arguments. This is known as
m(new Object()); generic programming.
}

public static void m(Object x) { • If a method’s parameter type is a


System.out.println(x.toString());
}
superclass (e.g., Object), you may pass
} an object to this method of any of the
parameter’s subclasses (e.g., Student or
class GraduateStudent extends Student { String).
}

class Student extends Person {


public String toString() { • When an object (e.g., a Student object
return "Student"; or a String object) is used in the
} method, the particular implementation
}
of the method of the object that is
class Person extends Object { invoked (e.g., toString) is determined
public String toString() { dynamically.
return "Person";
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
} rights reserved. 0132130807
• A subclass is a specialization of its superclass; every
instance of a subclass is also an instance of its
superclass, but not vice versa.
• In simple terms, polymorphism means that a variable
of a supertype can refer to a subtype object.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Casting Objects
You have already used the casting operator to convert variables of
one primitive type to another. Casting can also be used to convert
an object of one class type to another within an inheritance
hierarchy. In the preceding section, the statement
m(new Student());

assigns the object new Student() to a parameter of the Object type.


This statement is equivalent to:

Object o = new Student(); // Implicit casting


m(o);

The statement Object o = new Student(), known as


implicit casting, is legal because an instance of
Student is automatically an instance of Object.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
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
Casting from
Superclass to Subclass

Explicit casting must be used when casting an object from a superclass to a


subclass. This type of casting may not always succeed.

Apple x = (Apple)fruit;

Orange x = (Orange)fruit;

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
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
The instanceof Operator
If the superclass object is not an instance of the subclass, a runtime
ClassCastException occurs.

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
Example: Demonstrating Polymorphism and Casting

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
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. This implementation checks whether two reference variables
point to the same object using the == operator.
object1.equals(object2);

public boolean equals(Object obj) {

public boolean equals(Object o) {


For example, the if (o instanceof Circle) {
equals method is return radius == ((Circle)o).radius;
overridden in }
the Circle else
return false;
class. }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
The ArrayList and Vector
Classes
You can create an array to store objects. But the array’s size is fixed
once the array is created. Java provides the ArrayList class that can
be used to store an unlimited number of objects.
java.util.ArrayList
+ArrayList() Creates an empty list.
+add(o: Object) : void Appends a new element o at the end of this list.
+add(index: int, o: Object) : void Adds a new element o at the specified index in this list.
+clear(): void Removes all the elements from this list.
+contains(o: Object): boolean Returns true if this list contains the element o.
+get(index: int) : Object Returns the element from this list at the specified index.
+indexOf(o: Object) : int Returns the index of the first matching element in this list.
+isEmpty(): boolean Returns true if this list contains no elements.
+lastIndexOf(o: Object) : int Returns the index of the last matching element in this list.
+remove(o: Object): boolean Removes the element o from this list.
+size(): int Returns the number of elements in this list.
+remove(index: int) : Object Removes the element at the specified index.
+set(index: int, o: Object) : Object Sets the element at the specified index.

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

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

Modifier Accessed Accessed Accessed Accessed


on members from the from the from a from a different
in a class same class same package subclass package

public

protected -

default - -

private - - -

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Visibility Modifiers
package p1;
public class C1 { public class C2 {
public int x; C1 o = new C1();
protected int y; can access o.x;
int z; can access o.y;
private int u; can access o.z;
cannot access o.u;
protected void m() {
} can invoke o.m();
} }

package p2;

public class C3 public class C4 public class C5 {


extends C1 { extends C1 { C1 o = new C1();
can access x; can access x; can access o.x;
can access y; can access y; cannot access o.y;
can access z; cannot access z; cannot access o.z;
cannot access u; cannot access u; cannot access o.u;
can invoke m(); can invoke m(); cannot invoke o.m();
} } }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
A Subclass Cannot Weaken the
Accessibility
• A subclass may override a protected
method in its superclass and change its
visibility to public.
• However, a subclass cannot weaken the
accessibility of a method defined in the
superclass. For example, if a method is
defined as public in the superclass, it
must be defined as public in the
subclass.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
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
The final Modifier
• The final class cannot be extended:
• 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

You might also like