POLYMORPHISM
IN JAVA
1
Polymorphism in Java
• Polymorphism in Java is a concept by which we can perform a single action in different ways.
• Polymorphism is derived from 2 Greek words: poly and morphs.
"poly" means many
"morphs" means forms.
So polymorphism means many forms.
• There are two types of polymorphism in Java:
compile-time polymorphism and
runtime polymorphism.
• We can perform polymorphism in java by method overloading and method overriding.
• If you overload a static method in Java, it is the example of compile time polymorphism.
• Here, we will focus on runtime polymorphism in java.
2
Preface General
• We can treat an object of a subclass as an object of its superclass
• A reference variable of a superclass type can point to an object of its subclass Person
Person p = new Person (“Ahmad”, ‘M’, 55);
Employee e = new Employee("Susan", ‘F’, 45, 5250);
Person pe = new Employee (“Maha”, ‘F’, 33, 3000); Employee
double p, int e;
Special
p = e; // valid p = e;
e = p; // compiler error e = p;
e = new Person (); // compiler error e = 2.1;
e = (Employee) p; // runtime error
e = (Employee) pe; // valid e = (int) p;
3
Preface (continued)
• The reference variable
pe can point to any object of the
class Person or the class Employee
• These reference variable have many forms, that is, they are
polymorphic reference variables
• it can refer to objects of their own class or to objects of the
classes inherited from their class
4
Polymorphism and References
Shape myShape = new Circle(); // valid
Shape myShape2 = new Rectangle(); // valid
Shape myShape3 = new Square(); // valid
Rectangle myRectangle = new Shape(); // invalid
5
public class Person {
Very Important Notes: String name;
• If we have an object declared as follows: char gender;
int age;
Person pe = new Employee (“Maha”,‘F’, 33, 3000);
Person (String n, char g
Then the following statements are valid: int a) { … }
pe.isMale(); boolean isMale(){ … }
}
Employee e2 = (Employee) pe;
e2.getNetSalary(); public class Employee
extends Person {
But, the following statements are not valid:
pe.getNetSalary(); int salary;
pe.salary = 1000; Employee(String n, char g
int a, int s){…}
i.e. this object can only refer to the members of the superclass double getNetSalary() {
(from which it is declared) but …
can not refer to that of the subclass (from which it is created). }
• What about the overridden members??? }
6
Runtime Polymorphism in Java (Late Binding)
• Runtime polymorphism or Dynamic Method Dispatch is a process in
which a call to an overridden method is resolved at runtime rather than
at compile-time.
• In this process, an overridden method is called through the reference
variable of a superclass.
• The determination of the method to be called is based on the type of
the class it is created from.
• Polymorphism will assign multiple meanings to the same method
name.
7
public class Person {
String name;
Example 1: char gender;
int age;
• Person p = new Person (“Ahmad”, ‘M’, 55);
Person (String n, char g
int a) { … }
p.display();
// outputs: “In Person” boolean isMale(){ … }
p.getNetSalary(); void display()
// compiler error { S.o.p (“In Person”);}
}
• Employee e= new Employee("Susan",‘F’,45,5250);
public class Employee
e.display();
extends Person {
// outputs: “In Employee”
int salary;
e.getNetSalary();
Employee(String n, char g
int a, int s){…}
// outputs: salary after taxes
double getNetSalary() {
• Person pe= new Employee(“Maha”,‘F’, 33, 3000); …
pe.display(); }
// outputs: “In Employee” void display()
pe.getNetSalary(); { S.o.p (“In Employee”);}
// compiler error } 8
Example 2:
Shap [] shapes={ new Circle(…), new Rectangle(…),
new Square(…), new Circle(…),…};
double totalArea = 0.0;
for(Shape s : shapes){
totalArea += s.area(); //class Shape must have a method area
}
This is the polymorphism (same statement, many applications)
Assuming that class Shape has a method:
According to the data type of creation for each double area() { return 0.0; }
element in the array, the corresponding area() And this method is overridden in each of the
method is called automatically subclasses to reflect the calculation of actual area
of this shape
10
Why this method returns 0.0 ??? Can we do a better work ?!!!
Early Binding Polymorphism
• In Java, fields can be overridden in a subclass.
• If you define a field in a subclass with the same name as a field in the
superclass, the field in the subclass will hide (shadow) the field in the
superclass. If the subclass tries to access the field, it will access the
field in the subclass.
• If, however, the subclass calls up into a method in the superclass, and
that method accesses the field with the same name as in the
subclass, it is the field in the superclass that is accessed.
• Here is Java inheritance example that illustrates how fields in
subclasses shadow (hides) fields in superclasses:
11
public class Person {
Example 3: String name;
Person p = new Person ("aaa" , 20 , 'm'); char gender;
Employee e = new Employee("bbb", 30, 'f', 2000); int age;
String mobile = “010”;
Person pe = new Employee("zzz", 40, 'm', 3000); Person (String n, char g
int a) { … }
System.out.println("The data of the person "); void display()
{ S.o.p (mobile);}
p.display(); //outputs “010”
}
public class Employee
System.out.println("The data of the employee "); extends Person {
e.display(); //outputs “011”
int salary;
String mobile = “011”;
System.out.println("The data of the hybrid "); Employee(String n, char g
int a, int s){…}
pe.display(); //outputs “010” void display()
{ S.o.p (mobile);}12
}
Casting
Person p = new
• You cannot automatically make reference variable of subclass type Person (…);
points to object of its superclass.
e = p; // compiler error Employee e = new
Employee(…);
• Suppose that pe is a reference variable of a superclass type and pe Person pe = new
points to an object of its subclass: Employee (…);
• We can use a cast operator on pe and make a reference variable of the
subclass point to the object:
e = (Employee) pe; // valid
• If pe does not point to a subclass object and we use a cast operator on pe
to make a reference variable of the subclass point to this object, then Java
will throw a ClassCastException—indicating that the class cast is
not allowed.
e = (Employee) p;// runtime error ClassCastException 13
Person
Casting
• Example: Employee Student
Employee e1=new Person(); //not allowed
// a reference of subclass can not be used to handle an object of its superclass
Person p =new Employee(…); // allowed
Employee e2=p; //not allowed
Employee e3=(Employee)p; // this cast is allowed because p refers to Employee
Person p =new Student(…); // allowed
Employee e4=(Employee)p;
// allowed as a java syntax. i.e., there is no compiler error but through run time, Java will //throw a
ClassCastException—indicating that the class cast is not allowed 14
Why do we need casting? Person
methodP();
Person P1 = new Employee();
P1.methodP(); // calling the overridden method
P1.methodE(); // Error: not allowed
Employee
@override Student
methodP(); methodS();
Person P2 = new Student(); methodE();
P2.methodP(); // there is no overridden method, therefore,
// it makes calling for methodP() of Person
P2.methodS(); // Error: not allowed
15
Why do we need casting? Person
Person P1 = new Employee(); methodP();
P1.methodP(); // calling the overridden method
((Employee)P1).methodE(); // it is allowed
Therefore, we need to make casting to access the Employee
specialized members of the class Employee. @override Student
methodP(); methodS();
Note that specialized members of the class Employee mean that methodE();
members are not located in the class Person.
Person P2 = new Student();
P2.methodP(); // there is no overridden method, therefore,
// it makes calling for methodP() of Person
((Student) P2).methodS(); // it is allowed 16
Polymorphism (continued)
• Operator instanceof: determines whether a reference variable
that points to an object is of a particular class type
P1 instanceof Employee
This expression evaluates to true if P1 points to an object
of the class Employee; otherwise it evaluates to
false:
17
Polymorphism (continued)
Shap [] shapes={ new Circle(…), new Rectangle(…),
new Square(…), new Circle(…),…};
for( Shape s : shapes){
if( s instanceof Circle){
// casting s as Circle and use Circle method
}
else if( s instanceof Square){
// casting s as Square and use Square method
}
else if( s instanceof Recangle){ Note that the verification order. We check the
square type before the rectangle type because an
// casting s as Recangle and use Recangle method object of type square is already of type rectangle
} but not the opposite.
}
18