Object Oriented Programming in Java Lecture Note
Chapter 4: Polymorphism
4.1. Introduction
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. The word "poly" means many and "morphs" means forms. So,
polymorphism means many forms.
There are two types of polymorphism in Java: compile-time polymorphism (method overloading) and runtime
polymorphism (method overriding).
Method Overloading (Compile time Polymorphism) in Java
If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading. If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you
write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be
difficult for you as well as other programmers to understand the behavior of the method because its name differs.
Advantage of method overloading
Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
In Java, Method Overloading is not possible by changing the return type of the method only.
Example:
class Maths{
void sum(int a,int b){
System.out.println(a+b);
}
void sum(int a,int b,int c){
System.out.println(a+b+c);
}
void add(int a,int b){
1 | Page
Object Oriented Programming in Java Lecture Note
System.out.println(a+b);
}
void add(double a,double b){
System.out.println(a+b);
}
public static void main(String args[]){
Maths m=new Maths ();
m.sum(10,10,10);
m.sum(20,20);
m.add(10.5,10.5);
m.add(20,20);
} }
Method Overriding (Runtime Polymorphism) in Java
Runtime polymorphism is a process in which a call to an overridden method is resolved at runtime rather than
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 object being referred to by the reference variable.
Java Runtime Polymorphism Example:
Consider a scenario where Bank is a class that provides a method to get the rate of interest. However, the rate of
interest may differ according to banks. For example, CBE, Enat, and Abay banks are providing 8.4%, 7.3%, and
9.7% rate of interest.
class Bank{ class Enat extends Bank{
float getRateOfInterest(){ float getRateOfInterest(){
return 0; return 7.3f;
} }
} }
class CBE extends Bank{ class Abay extends Bank{
float getRateOfInterest(){ float getRateOfInterest(){
return 8.4f; return 9.7f;
} }
} }
2 | Page
Object Oriented Programming in Java Lecture Note
public class TestPolymorphism{
public static void main(String args[]){
Bank b;
b=new CBE();
System.out.println("CBE Rate of Interest: "+b.getRateOfInterest());
b=new Enat();
System.out.println("Enat Bank Rate of Interest: "+b.getRateOfInterest());
b=new Abay();
System.out.println("Abay Bank Rate of Interest: "+b.getRateOfInterest());
} }
Difference between Method Overloading and Method Overriding in java
No. Method Overloading Method Overriding
used to provide the specific implementation
1 used to increase the readability of the program. of the method that is already provided by its
super class.
occurs in two classes that have IS-A
2 performed within class.
(inheritance) relationship.
3 parameter must be different. parameter must be same.
4 example of compile time polymorphism. example of runtime polymorphism.
can't be performed by changing return type of
Return type must be same or covariant in
5 the method only. Return type can be same or
method overriding.
different in method overloading.
4.2. Assigning subclass object to a superclass variable
If you assign an object of the subclass to the reference variable of the superclass then the subclass object is
converted into the type of superclass and this process is termed as widening (in terms of references). But, using
this reference you can access the members of superclass only if you try to access the subclass members a
compile-time error will be generated.
We can cast/convert an object of one class type to others. But these two classes should be in an inheritance
relation. Then,
▪ If you convert a Super class to subclass type it is known as narrowing in terms of references (Subclass
reference variable holding an object of the superclass).
Sub sub = (Sub)new Super();
▪ If you convert a Sub class to Super class type it is known as widening in terms of references (super class
reference variable holding an object of the sub class).
Super sup = new Sub();
3 | Page
Object Oriented Programming in Java Lecture Note
Example
In the following Java example, we have two classes namely Person and Student. The Person class has two
instance variables name and age and one instance method displayperson() which displays the name and age.
The Student class extends the person class and in addition to the inherited name and age, it has two more
variables department and student_id. It has a method displaydata() which displays all four values.
In the main method, we are assigning the subclass object with the superclass reference variable
class Person{
public String name;
public int age;
public Person(String name, int age){
this.name = name;
this.age = age;
}
public void displayPerson() {
System.out.println("Data of the Person class: ");
System.out.println("Name: "+this.name);
System.out.println("Age: "+this.age);
}
}
public class Student extends Person {
public String department;
public int Student_id;
public Student(String name, int age, String department, int Student_id){
super(name, age);
this. department = department;
this.Student_id = Student_id;
}
public void displayStudent() {
System.out.println("Data of the Student class: ");
System.out.println("Name: "+super.name);
System.out.println("Age: "+super.age);
System.out.println("Department: "+this. department);
System.out.println("Student ID: "+this.Student_id);
}
4 | Page
Object Oriented Programming in Java Lecture Note
public static void main(String[] args) {
Person person = new Student("Krishna", 20, "IT", 1256);
person.displayPerson();
}
}
Accessing the subclass methods
When you assign the subclass object to the superclass reference variable and, using this reference if you try to
access the members of the subclass a compile-time error will be generated.
Example
In this case, if you assign a Student object to reference variable of Person class as
Person person = new Student("Krishna", 20, "IT", 1256);
Using this reference, you can access the method of the superclass only i.e. displayperson(). Instead, if you try to
access the subclass method i.e. displaystudent() a compile-time error is generated.
Therefore, if you replace the main method of the previous program with the following a compile-time error will
be generated.
public static void main(String[] args) {
Person person = new Student("Krishna", 20, "IT", 1256);
person.displayStudent();
Referencing Subclass objects with Subclass vs Superclass reference
In java inheritance some of the basic rules includes −
• Object relation of Superclass (parent) to Subclass (child) exists while child to parent object relation never
exists. This means that reference of parent class could hold the child object while child reference could
not hold the parent object.
• In case of overriding of non-static method the runtime object would evaluate that which method would be
executed of subclass or of superclass. While execution of static method depends on the type of reference
that object holds.
• Other basic rule of inheritance is related to static and non-static method overriding that static method in
java could not be overridden while non static method can be. However, subclass can define static method
of same static method signature as superclass have hut that would not be consider as overriding while
known as hiding of static method of superclass.
On the basis of above rules, we would observe different scenarios with the help of program.
5 | Page
Object Oriented Programming in Java Lecture Note
Example
class Parent {
public void parentPrint() {
System.out.println("parent print called");
}
public static void staticMethod() {
System.out.println("parent static method called");
}
}
public class SubclassReference extends Parent {
public void parentPrint() {
System.out.println("child print called");
}
public static void staticMethod() {
System.out.println("child static method called");
}
public static void main(String[] args) {
/*SubclassReference invalid = new Parent();//Type mismatch: cannot convert from Parent to
SubclassReference*/
Parent obj = new SubclassReference();
obj.parentPrint(); //method of subclass would execute as subclass object at runtime.
obj.staticMethod(); //method of superclass would execute as reference of superclass.
Parent obj1 = new Parent();
obj1.parentPrint(); //method of superclass would execute as superclass object at runtime.
obj1.staticMethod(); //method of superclass would execute as reference of superclass.
SubclassReference obj3 = new SubclassReference();
obj3.parentPrint(); //method of subclass would execute as subclass object at runtime.
obj3.staticMethod(); //method of subclass would execute as reference of subclass.
}
}
So difference between referencing using superclass reference and referencing using subclass reference is use
superclass referencing can holds object of subclass and could only access the methods which are
defined/overridden by subclass while use subclass referencing cannot hold object of superclass and could access
the methods of both superclass and subclass.
6 | Page
Object Oriented Programming in Java Lecture Note
4.3. Multiple Inheritance and Interfaces
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS
where you type the text and send the message. You don't know the internal processing about the message
delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
Abstract class in Java
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method implemented. It cannot be instantiated.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the method.
Abstract Method in Java
A method which is declared as abstract and does not have implementation is known as an abstract method.
Example of abstract method
abstract void printStatus();//no method body and abstract
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods. The interface in Java
is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method
body. It is used to achieve abstraction and multiple inheritance in Java. In other words, you can say that
interfaces can have abstract methods and variables. It cannot have a method body.
7 | Page
Object Oriented Programming in Java Lecture Note
Java Interface also represents the IS-A relationship.
It cannot be instantiated just like the abstract class.
Why use Java interface?
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
How to declare an interface?
An interface is declared by using the interface keyword. It provides total abstraction. All the methods in an
interface are declared with the empty body, and all the fields are public, static and final by default. A class that
implements an interface must implement all the methods declared in the interface.
The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds public, static and
final keywords before data members.
In other words, Interface fields are public, static and final by default, and the methods are public and abstract.
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple
inheritance.
8 | Page
Object Oriented Programming in Java Lecture Note
Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods.
Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
Abstract class Interface
can have abstract and non-abstract methods. can have only abstract methods.
doesn't support multiple inheritance. supports multiple inheritance.
can have final, non-final, static and non-static variables. has only static and final variables.
can provide the implementation of interface. can't provide the implementation of abstract class.
The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.
can extend another Java class and implement multiple
can extend another Java interface only.
Java interfaces.
can be extended using keyword "extends". can be implemented using keyword "implements".
can have class members like private, protected, etc. Members of a Java interface are public by default.
9 | Page