0% found this document useful (0 votes)
45 views24 pages

Polymorphism: Cse215: Programming Language Ii Silvia Ahmed (Sva)

1) The document discusses polymorphism through an example program that passes different object types (GraduateStudent, Student, Person, Object) to a method (m) that accepts a parameter of type Object. 2) The m method calls the toString method on the passed object. Polymorphism allows the correct overridden toString method to be called based on the actual object type. 3) Dynamic binding determines which toString implementation is used at runtime based on the object's most specific type, allowing polymorphic usage of methods on varied arguments.

Uploaded by

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

Polymorphism: Cse215: Programming Language Ii Silvia Ahmed (Sva)

1) The document discusses polymorphism through an example program that passes different object types (GraduateStudent, Student, Person, Object) to a method (m) that accepts a parameter of type Object. 2) The m method calls the toString method on the passed object. Polymorphism allows the correct overridden toString method to be called based on the actual object type. 3) Dynamic binding determines which toString implementation is used at runtime based on the object's most specific type, allowing polymorphic usage of methods on varied arguments.

Uploaded by

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

Lecture 10

Polymorphism

Department of Electrical and Computer Engineering,

North South University

Silvia Ahmed (SvA) CSE215: Programming Language II 1


An Example
public class PolymorphismDemo {

public static void main(String[] args) {


m(new GraduateStudent());
Object +toString()
m(new Student());
m(new Person());
m(new Object());
}

public static void m(Object x) {


System.out.println(x.toString()); Person +toString()
}
}

class GraduateStudent extends Student {


}
Student +toString()
class Student extends Person {
public String toString() {
return "Student";
}
}
GraduateStudent
class Person extends Object {
public String toString() {
return "Person";
}
}
Silvia Ahmed (SvA) CSE215: Programming Language II 2
An Example (contd.)
public class PolymorphismDemo {
Object +toString()
public static void main(String[] args) {
m(new GraduateStudent());
m(new Student()); Person +toString()
m(new Person());
m(new Object());
}
Student +toString()
public static void m(Object x) {
System.out.println(x.toString());
} GraduateStudent
}

class GraduateStudent extends Student {


}

class Student extends Person {


Q1: Is this possible to pass an
public String toString() {
return "Student";
object of type GraduateStudent
} where an Object type is
}
required?
class Person extends Object {
public String toString() {
return "Person";
}
}
Silvia Ahmed (SvA) CSE215: Programming Language II 3
An Example (contd.)
Q1: Is this possible to pass an object of type GraduateStudent
where an Object type is required?

Object +toString() Object

Person +toString() Person

Student +toString() Student

GraduateStudent GraduateStudent

• Every subtype object is also an object of its supertype.


• So we can pass an object of subtype (eg. GraduateStudent, or
Student) when an object of supertype (here: Object) is required.
Silvia Ahmed (SvA) CSE215: Programming Language II 4
Polymorphism
public class PolymorphismDemo {
Method m takes a parameter
public static void main(String[] args) {
m(new GraduateStudent()); of the Object type. You can
m(new Student()); invoke it with any object.
m(new Person());
m(new 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.
}
}

class GraduateStudent extends Student {


}
When the method m(Object x) is executed, the
argument x’s toString method is invoked. x may
class Student extends Person {
public String toString() { be an instance of GraduateStudent, Student,
return "Student"; Person, or Object. Classes GraduateStudent,
}
} Student, Person, and Object have their own
class Person extends Object {
implementation of the toString method. Which
public String toString() { implementation is used will be determined
return "Person";
}
dynamically by the Java Virtual Machine at
} runtime. This capability is known as dynamic
binding.
Silvia Ahmed (SvA) CSE215: Programming Language II 5
An Example (contd.)
public class PolymorphismDemo {
Object +toString()
public static void main(String[] args) {
m(new GraduateStudent());
m(new Student()); Person +toString()
m(new Person());
m(new Object());
}
Student +toString()
public static void m(Object x) {
System.out.println(x.toString());
} GraduateStudent
}

class GraduateStudent extends Student {


}

class Student extends Person {


Q2: Which overriden method of
public String toString() {
return "Student";
toString() will be executed, when
} different types of objects are
}
passed into the method m()?
class Person extends Object {
public String toString() {
return "Person";
}
}
Silvia Ahmed (SvA) CSE215: Programming Language II 6
An Example (contd.)
Q2: Which overriden method of toString() will be executed,
when different types of objects are passed into the method m()?

Object +toString()
Polymorphism enables us to write the
following line of code:
Person +toString()

Object o = new Student();


Student +toString()
Here,
GraduateStudent Object: o’s Declared type
Student: o’s Actual type

• Which toString() method is invoked by o is determined by o’s


actual type

Silvia Ahmed (SvA) CSE215: Programming Language II 7


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.

Silvia Ahmed (SvA) CSE215: Programming Language II 8


Method Matching vs Dynamic 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.

Silvia Ahmed (SvA) CSE215: Programming Language II 9


Generic Programming
public class PolymorphismDemo { • Polymorphism allows methods to be
public static void main(String[] args) { used generically for a wide range of
m(new GraduateStudent());
m(new Student()); object arguments. This is known as
m(new Person());
m(new Object());
generic programming.
}
• If a method’s parameter type is a
public static void m(Object x) { superclass (e.g., Object), you may pass
System.out.println(x.toString());
}
an object to this method of any of the
} parameter’s subclasses (e.g., Student
class GraduateStudent extends Student { or String).
}
• When an object (e.g., a Student object
class Student extends Person { or a String object) is used in the
public String toString() {
return "Student"; method, the particular implementation
} of the method of the object that is
}
invoked (e.g., toString) is determined
class Person extends Object { dynamically.
public String toString() {
return "Person";
}
}

Silvia Ahmed (SvA) CSE215: Programming Language II 10


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.
Silvia Ahmed (SvA) CSE215: Programming Language II 11
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


Silvia Ahmed (SvA) CSE215: Programming Language II 12
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;

Why?

Silvia Ahmed (SvA) CSE215: Programming Language II 13


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());
...
}

Silvia Ahmed (SvA) CSE215: Programming Language II 14


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.

Silvia Ahmed (SvA) CSE215: Programming Language II 15


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


}
• This method often should be overridden in the user defined classes.
For example, the public boolean equals(Object o) {
if (o instanceof Circle) {
equals method is return radius == ((Circle)o).radius;
overridden in }
the Circle else
class. return false;
}
Silvia Ahmed (SvA) CSE215: Programming Language II 16
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.

Silvia Ahmed (SvA) CSE215: Programming Language II 17


The ArrayList Class
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.

Silvia Ahmed (SvA) CSE215: Programming Language II 18


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

Silvia Ahmed (SvA) CSE215: Programming Language II 19


Accessibility Summary

Silvia Ahmed (SvA) CSE215: Programming Language II 20


Visibility Modifiers

Silvia Ahmed (SvA) CSE215: Programming Language II 21


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.
Silvia Ahmed (SvA) CSE215: Programming Language II 22
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.

Silvia Ahmed (SvA) CSE215: Programming Language II 23


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.

Silvia Ahmed (SvA) CSE215: Programming Language II 24

You might also like