You are on page 1of 71

Unit-III

Part-II
Polymorphism

Polymorphism in java is a concept by which we can


perform a single action by 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 and
• Runtime Polymorphism.

We can perform polymorphism in java by method


overloading and method overriding.

If you overload static method in java, it is the example of


compile time polymorphism.
class DemoOverload
{
public int add(int x, int y) //method 1

return x+y;
}
public int add(int x, int y, int z) //method 2
{
return x+y+z;
}
public int add(double x, int y) //method 3
{
return (int)x+y;
}
public int add(int x, double y) //method 4
{
return x+(int)y;
}
}
class Test
{
public static void main(String[] args)
{
DemoOverload demo=new DemoOverload();
System.out.println(demo.add(2,3));      //method 1 called
System.out.println(demo.add(2,3,4));    //method 2 called
System.out.println(demo.add(2,3.4));    //method 4 called
System.out.println(demo.add(2.5,3));    //method 3 called
}
}
In the above example, there are four versions
of add methods. The first method takes two parameters
while the second one takes three. For the third and fourth
methods there is a change of order of parameters.  The
compiler looks at the method signature and decides
which method to invoke for a particular method call at
compile time.
Runtime Polymorphism
Runtime polymorphism or Dynamic Method
Dispatch 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.
class A{}  
class B extends A{}  
A a=new B();//upcasting  
class Bike
{  
   void run()
{
System.out.println("running");
}  
}  
class Splender extends Bike
{  
void run()
{
System.out.println("running safely with 60km");
}  
 public static void main(String args[])
{  
    Bike b = new Splender(); //upcasting  
     b.run();  
  }  
}  
Output:
running safely with 60km.

In this example, we are creating two classes Bike and


Splendar. Splendar class extends Bike class and overrides
its run() method. We are calling the run method by the
reference variable of Parent class. Since it refers to the
subclass object and subclass method overrides the Parent
class method, subclass method is invoked at runtime.
Example: Bank
class Bank
{  
float getRateOfInterest()
{ return 0; }  
}  
class SBI extends Bank
{  
float getRateOfInterest()
{ return 8.4f;}  
}  
class ICICI extends Bank
{  
float getRateOfInterest()
{ return 7.3f;}  
}  
class AXIS extends Bank
{  
float getRateOfInterest()
{ return 9.7f;}  
}  
class TestPolymorphism
{  
public static void main(String args[])
{  
Bank b;  
b=new SBI();  
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());  
b=new ICICI();  
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());  
b=new AXIS();  
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());  
}  
}  

Output:
SBI Rate of Interest: 8.4
ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7
Runtime Polymorphism with Data
Member
Method is overridden not the data members, so runtime
polymorphism can't be achieved by data members.
class Bike
{  
 int speedlimit=90;  
}  
class Honda3 extends Bike
{  
 int speedlimit=150;  
    public static void main(String args[])
{  
Bike obj=new Honda3();  
System.out.println(obj.speedlimit);//90  
}
}  

Output:
90
In the given example, both the classes have a data
member speedlimit, we are accessing the data member by
the reference variable of Parent class which refers to the
subclass object. Since we are accessing the data member
which is not overridden, hence it will access the data
member of Parent class always.
Runtime Polymorphism with Multilevel
Inheritance
class Animal
{  
void eat()
{
System.out.println("eating");
}  
}  
class Dog extends Animal
{  
void eat()
{
System.out.println("eating fruits");
}  
}  
class BabyDog extends Dog
{  
void eat()
{
System.out.println("drinking milk");
}  

public static void main(String args[])
{  
Animal a1,a2,a3;  
a1=new Animal();  
a2=new Dog();  
a3=new BabyDog();  
a1.eat();  
a2.eat();  
a3.eat();  
}  
}
Output:
eating
eating fruits
drinking Milk
Example:
class Animal
{  
void eat(){System.out.println("animal is eating...");}  
}  
class Dog extends Animal
{  
void eat(){System.out.println("dog is eating...");}  
}  
class BabyDog1 extends Dog
{  
public static void main(String args[]){  
Animal a=new BabyDog1();  
a.eat();  
}
}  
Output:
Dog is eating

Since, BabyDog is not overriding the eat() method, so eat()


method of Dog class is invoked.
Inheritance 
The process by which one class acquires the
properties(data members) and functionalities(methods) of
another class is called inheritance.
The aim of inheritance is to provide the reusability of
code so that a class has to write only the unique features
and rest of the common properties and functionalities can
be extended from the another class.
Child Class:
The class that extends the features of another class is
known as child class, sub class or derived class.

Parent Class:
The class whose properties and functionalities are
used(inherited) by another class is known as parent class,
super class or Base class.
So, the Inheritance is a process of defining a new class
based on an existing class by extending its common data
members and methods.

Inheritance allows us to reuse of code, it improves


reusability in your java application.

The biggest advantage of Inheritance is that the code


that is already present in base class need not be rewritten
in the child class.

This means that the data members(instance variables)


and methods of the parent class can be used in the child
class as.
Syntax: 
To inherit a class we use extends keyword.
Example:
class XYZ extends ABC
{
}
Here class XYZ is child class and class ABC is parent
class. The class XYZ is inheriting the properties and
methods of ABC class. 
Example:
class Teacher
{
String designation = “Teacher”;
String collegeName = “AMU”;
void does()
{
System.out.println("Teaching");
}
}
public class CompTeacher extends Teacher
{
String mainSubject = “Computer”;
public static void main(String args[])
{
CompTeacher obj = new CompTeacher ();
System.out.println(obj.collegeName);
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.does();
}
}
Output:
AMU
Teacher
Computer
Teaching
Note:
The derived class inherits all the members and methods
that are declared as public or protected. If the members or
methods of super class are declared as private then the
derived class cannot use them directly. The private
members can be accessed only in its own class. Such
private members can only be accessed using public or
protected getter and setter methods of super class as
shown in the next example.
class Teacher
{
private String designation = "Teacher";
private String collegeName = “AMU";
public String getDesignation()
{
return designation;
}
protected void setDesignation(String designation)
{
this.designation = designation;
}
protected String getCollegeName()
{
return collegeName;
}
protected void setCollegeName(String collegeName)
{
this.collegeName = collegeName;
}
void does()
{
System.out.println("Teaching");
}
}
public class JavaExample extends Teacher
{
String mainSubject = “Computer";
public static void main(String args[])
{
JavaExample obj = new JavaExample();
/* Note: we are not accessing the data members

* directly we are using public getter method

* to access the private members of parent class

*/

System.out.println(obj.getCollegeName());
System.out.println(obj.getDesignation());
System.out.println(obj.mainSubject);

obj.does();

}
The Output is:
AMU
Teacher
Computer
Teaching

The child class is able to access the private members of


parent class through protected methods of parent class.
When we make a instance variable(data member) or
method protected, this means that they are accessible only
in the class itself and in child class. 
Types of Inheritance
• Single Inheritance: 
It refers to a child and parent class relationship where a
class extends the another class.

Single Inheritance
• Multilevel Inheritance: 
It refers to a child and parent class relationship where a
class extends the child class. For example class C
extends class B and class B extends class A.

C Multilevel Inheritance
class Car
{
public Car()
{
System.out.println("Class Car");
}
public void vehicleType()
{
System.out.println("Vehicle Type: Car");
}
}
class Maruti extends Car
{
public Maruti()
{
System.out.println("Class Maruti");
}
public void brand()
{
System.out.println("Brand: Maruti");
}
public void speed()
{
System.out.println("Max: 90Kmph");
}
}
public class Maruti800 extends Maruti
{
public Maruti800()
{
System.out.println("Maruti Model: 800");
}
public void speed()
{
System.out.println("Max: 80Kmph");
}
public static void main(String args[])
{ Maruti800 obj=new Maruti800();
obj.vehicleType(); obj.brand(); obj.speed();
}
}
Output:
Class Car
Class Maruti
Maruti Model: 800
Vehicle Type: Car
Brand: Maruti
Max: 80Kmph
• Hierarchical Inheritance:
It refers to a child and parent class relationship where
more than one classes extends the same class. For
example, classes B, C & D extends the same class A.

B C D

Hierarchical Inheritance
class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
class JavaExample
{
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
//All classes can access the method of class A
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}
Output:
method of Class A
method of Class A
method of Class A
• Multiple Inheritance:
It refers to the concept of one class extending more than
one classes, which means a child class has two parent
classes. For example class C extends both classes A and
B. Java doesn’t support multiple inheritance.

A B

C Multiple Inheritance
• Hybrid Inheritance:
Combination of more than one types of inheritance in a
single program.
For example class A & B extends class C and another
class D extends class A then this is a hybrid inheritance
example because it is a combination of single and
hierarchical inheritance. A

B C
Hybrid Inheritance D
class C
{
public void disp()
{
System.out.println("C");
}
}
class A extends C
{
public void disp()
{
System.out.println("A");
}
}
class B extends C
{
public void disp()
{
System.out.println("B");
}
}
class D extends A
{
public void disp()
{
System.out.println("D");
}
public static void main(String args[])
{
D obj = new D();
obj.disp();
}
}

Output:
D
What all can be done in a Subclass
In sub-classes we can inherit members as is, replace them,
hide them, or supplement them with new members:
 The inherited fields can be used directly, just like any
other fields.
 We can declare new fields in the subclass that are not in
the super class.
 The inherited methods can be used directly as they are.
 We can write a new instance method in the subclass
that has the same signature as the one in the super
class, thus overriding it.

 We can write a new static method in the subclass that


has the same signature as the one in the super class,
thus hiding it.

 We can declare new methods in the subclass that are


not in the super class.

 We can write a subclass constructor that invokes the


constructor of the super class, either implicitly or by
using the keyword super.
Constructors and Inheritance
Constructor of sub class is invoked when we create the
object of subclass, it by default invokes the default
constructor of super class.

Hence, in inheritance the objects are constructed top-


down. The super class constructor can be called explicitly
using the super keyword, but it should be first statement in
a constructor.

The super keyword refers to the super class,


immediately above of the calling class in the hierarchy. The
use of multiple super keywords to access an ancestor class
other than the direct parent is not permitted. 
class ParentClass
{
//Parent class constructor
ParentClass()
{
System.out.println("Constructor of Parent");
}
}
class JavaExample extends ParentClass
{
JavaExample()
{
/* It by default invokes the constructor of parent class
* You can use super() to call the constructor of parent.
* It should be the first statement in the child class
* constructor, you can also call the parameterized constructor
* of parent class by using super like this: super(10), now
* this will invoke the parameterized constructor of int arg
*/
System.out.println("Constructor of Child");
}
public static void main(String args[])
{
//Creating the object of child class
new JavaExample();
}
}
Output:
Constructor of Parent
Constructor of Child
Inheritance and Method Overriding
When we declare the same method in child class which is
already present in the parent class the this is
called method overriding. 
In this case when we call the method from child class
object, the child class version of the method is called.
However we can call the parent class method using super
keyword.
class ParentClass
{
//Parent class constructor
ParentClass()
{
System.out.println("Constructor of Parent");
}
void disp()
{
System.out.println("Parent Method");
}
}
class JavaExample extends ParentClass
{
JavaExample()
{
System.out.println("Constructor of Child");
}
void disp()
{
System.out.println("Child Method");
//Calling the disp() method of parent class
super.disp();
}
public static void main(String args[])
{
//Creating the object of child class
JavaExample obj = new JavaExample();
obj.disp();
}
}
The Output is :
Constructor of Parent
Constructor of Child
Child Method
Parent Method
‘Super’ keyword
The super keyword refers to the objects of immediate
parent class. 
The use of super keyword:
1. To access the data members of parent class when both
parent and child class have member with same name.
2. To explicitly call the no-arg and parameterized
constructor of parent class.
3. To access the method of parent class when child class
has overridden that method.
1. How to use super keyword to access the variables of
parent class

When you have a variable in child class which is already


present in the parent class then in order to access the
variable of parent class, you need to use the super
keyword.
class Superclass
{
int num = 100;
}
class Subclass extends Superclass
{
int num = 110;
void printNumber()
{
System.out.println(num);
}
public static void main(String args[])
{
Subclass obj= new Subclass();
obj.printNumber();
}
}
Output: 110
Accessing the num variable of parent class:
By calling a variable like this, we can access the variable of
parent class if both the classes (parent and child) have same
variable.
super.variable_name
class Superclass
{
int num = 100;
}
class Subclass extends Superclass
{
int num = 110;
void printNumber()
{
System.out.println(super.num);
}
public static void main(String args[])
{
Subclass obj= new Subclass();
obj.printNumber();
}
}
Output: 100
2. Use of super keyword to invoke constructor of
parent class

When we create the object of sub class, the new


keyword invokes the constructor of child class, which
implicitly invokes the constructor of parent class.
So the order to execution when we create the object of
child class is: parent class constructor is executed first and
then the child class constructor is executed.
It happens because compiler itself adds super()(this
invokes the no-arg constructor of parent class) as the first
statement in the constructor of child class.
class Parentclass
{
Parentclass()
{
System.out.println("Constructor of parent class");
}
}
class Subclass extends Parentclass
{
Subclass()
{
System.out.println("Constructor of child class");
}
Subclass(int num)
{
System.out.println("arg constructor of child class");
}
void display()
{
System.out.println("Hello!");
}
public static void main(String args[])
{
Subclass obj= new Subclass();
Subclass obj2= new Subclass(10);
obj2.display();
}
}
Output:
Constructor of parent class
Constructor of child class
Constructor of parent class
arg constructor of child class
Hello!
Parameterized super() call to invoke parameterized
constructor of parent class

We can call super() explicitly in the constructor of child


class, but it would not make any sense because it would be
redundant. It’s like explicitly doing something which
would be implicitly done otherwise.
However when we have a constructor in parent class
that takes arguments then we can use parameterized super,
like super(100); to invoke parameterized constructor of
parent class from the constructor of child class.
class Parentclass
{
Parentclass()
{
System.out.println("no-arg constructor of parent class");
}
Parentclass(String str)
{
System.out.println("parameterized constructor of parent class");
}
}
class Subclass extends Parentclass
{
Subclass()
{
super("Hahaha");
System.out.println("Constructor of child class");
}
void display()
{
System.out.println("Hello");
}
public static void main(String args[])
{
Subclass obj= new Subclass();
obj.display();
}
}

Output:
parameterized constructor of parent class
Constructor of child class
Hello
There are few important points to note in this example:
1) super() or parameterized super must be the first
statement in constructor otherwise you will get the
compilation error: “Constructor call must be the first
statement in a constructor”
2) When we explicitly placed super in the constructor, the
java compiler didn’t call the default no-arg constructor
of parent class.
3. How to use super keyword in case of method
overriding

When a child class overrides a method of parent class,


then the call to the method from child class object always
call the child class version of the method. However by
using super keyword like this: super.method_name we can
call the method of parent class (the method which is
overridden).
class Parentclass
{
void display()
{
System.out.println("Parent class method");
}
}
class Subclass extends Parentclass
{
void display()
{
System.out.println("Child class method");
}
void printMsg()
{
display();
super.display();
}
public static void main(String args[])
{
Subclass obj= new Subclass();
obj.printMsg();
}
}

Output:
Child class method
Parent class method

You might also like