| Java Polymorphism |
JAVA POLYMORPHISM
POLYMORPHISM
• Poly means “many” and morphs means “forms”. So, polymorphism
means many forms. (Having many forms)
• If a same method / single method performs different operations with
same / different signatures, then it is called as polymorphism.
• Signature (Number of arguments, Type of arguments)
• One name many forms
• One of the core object oriented programming technique.
Use
• It is mainly used to implement the concept of inheritance in oops.
Vehicle
Bus Train Car Bike
Figure: Polymorphism
1
| Java Polymorphism |
TYPES OF POLYMORPHISM
• In java, polymorphism is classified as two types. They are
1. Compile Time Polymorphism
2. Run Time Polymorphism.
Polymorphism
Compile Time Run Time
Polymorphism Polymorphism
Examples Examples
1. Method Overloading 1. Method Overriding (Java & C#)
2. Constructor Overloading
Figure: Types of Polymorphism
NOTE
• It is important to note that, java does not support operator
overloading.
2
| Java Polymorphism |
I. COMPILE TIME POLYMORPHISM
• Same function (single function) performs different operations using
different signatures
• Signatures Number of arguments, Type of arguments
• This is called using its signatures
• Ex.
1. Method overloading
2. Constructor overloading.
Method Overloading
• If same method / single method takes one or more number of
arguments that is called as method overloading
• Same method (single method) performs different operations using
different set of signatures
• This is called by using its signatures
▪ Types of arguments → (int, float, void, char)
▪ Number of arguments → (0,1,2,3, … n)
• Types
1. Argument based function overloading
2. Type based function overloading.
1. Argument based function overloading
• If same function performs different operations using different set of
arguments (0, 1, 2, etc, …) then is called as argument-based function
overloading
• It gives the importance to arguments (not types)
• This is called by using its signatures. Here the signature depends on
the number of arguments (not types)
Calling
• Calling is purely based on arguments order. It does not
provide the priority to data types.
3
| Java Polymorphism |
2. Type based function overloading
• If same function performs different operations using different set of
types (int, float, double, etc, …) then it is called as type based function
overloading
• It gives the importance to data types (not arguments)
• This is called by using its signatures. Here the signature depends on
the data types of methods
Calling
• Calling is purely based on types. It does not provide the
priority to number of arguments.
DIFFERENCE BETWEEN OVERLOADING AND OVERRIDING
S.N Overloading Overriding
1. Same method with different Same method with different
operations using different operations using same
signatures signatures
2. Compile time polymorphism Runtime polymorphism (dynamic
(static binding or early binding) binding or late binding)
3. It does not need inheritance It needs inheritance to achieve
overriding concept
4. Calling is based on its This is implemented using super
signatures keyword
5. Method can use different Here, method should use same
access modifier for each modifier for each method
method
4
| Java Polymorphism |
I. TYPE BASED METHOD OVERLOADING
(Type_Overloading.java)
1. SOURCE CODE
class Moverloading
{
final float PI=3.14f; // constant variable
// area of the square
public int area(int x)
{
return(x*x);
}
// area of the circle
public double area(double r)
{
return(PI*r*r);
}
// area of the rectangle
public long area(int l, int b)
{
return(l*b);
}
}
// main class
public class Type_Overloading
{
// main method
public static void main(String[] args)
{
[Link]("==============================");
[Link]("\t\tType Based Method Overloading");
[Link]("===============================");
// object creation using new modifier
Moverloading obj=new Moverloading();
5
| Java Polymorphism |
// calling method overloading using its type based signatures
double circle=[Link](10.0);
int square=[Link](5);
long rect=[Link](100, 10);
// print the result
[Link]("Area of the Circle \t:"+circle+"\t(<-Java Style)");
[Link]("Area of the Circle \t:%6.2f\t\t\t(<-C Style)\n",circle);
[Link]("Area of the Square \t:"+square);
[Link]("Area of the Rectangle \t:"+square);
[Link]("----------------------------------------------------");
}
}
2. OUTPUT
6
| Java Polymorphism |
II. ARGUMENT BASED METHOD OVERLOADING
(Argument_Overloading.java)
1. SOURCE CODE
class Aoverloading
{
// zero argument overloading
void info()
{
[Link]("Zero Argument");
}
// one argument overloading
void info(int k)
{
[Link]("One Argument");
[Link]("\tk= "+k);
}
// two arguments overloading
void info(int id, String name)
{
[Link]("Two Arguments");
[Link]("\tName= "+name);
[Link]("\tId= "+id);
}
// one argument overloading
void info(double d)
{
[Link]("One Argument");
[Link]("\td= "+d);
}
}
7
| Java Polymorphism |
// main class
public class Argument_Overloading
{
// main method
public static void main(String[] args)
{
[Link]("====================================");
[Link]("\tArgument Based Method Overloading");
[Link]("====================================");
// object creation using new modifier
Aoverloading obj=new Aoverloading();
// calling method overloading using its argument based signatures
[Link](10.0);
[Link]("----------------------------------------------------");
[Link](33,"Sachin");
[Link]("----------------------------------------------------");
[Link]();
[Link]("----------------------------------------------------");
[Link](281);
[Link]("----------------------------------------------------");
}
}
8
| Java Polymorphism |
2. OUTPUT
9
| Java Polymorphism |
CONSTRUCTOR OVERLOADING
• If a same constructor performs different operations with different set of
arguments, then it is called as constructor overloading.
• Constructor supports ONLY arguments based overloading. It does
not support type based overloading. Because it does not return any
type of data.
Calling
• Constructor overloading is called by its signature (order of
arguments)
• The arguments in the constructor call must match the
constructor definition inside the class else it will provide the
error message.
III. ARGUMENT BASED CONSTRUCTOR OVERLOADING
(Argu_Overloading.java)
1. SOURCE CODE
public class Argu_Overloading
{
// zero argument constructor overloading
Argu_Overloading()
{
[Link]("Zero Argument Constructor");
}
// one argument constructor overloading
Argu_Overloading(int a)
{
[Link]("One Argument Constructor");
[Link]("\tint value="+a);
}
10
| Java Polymorphism |
// one argument constructor overloading
Argu_Overloading(float a)
{
[Link]("One Argument Constructor");
[Link]("\tfloat value="+a);
}
// two arguments constructor overloading
Argu_Overloading(int a, String str)
{
[Link]("Two Arguments Constructor");
[Link]("\tid="+a);
[Link]("\tname="+str);
}
// main method
public static void main(String[] args)
{
[Link]("==============================");
[Link]("\tArgument Based Constructor Overloading");
[Link]("==============================");
// calling 1-argument constructor
Argu_Overloading a1=new Argu_Overloading(54);
[Link]("----------------------------------------------------");
// calling 0-argument constructor
Argu_Overloading a2=new Argu_Overloading();
[Link]("----------------------------------------------------");
// calling 2-arguments constructor
Argu_Overloading a3=new Argu_Overloading(23,"Sachin");
[Link]("----------------------------------------------------");
// calling 1-argument constructor
Argu_Overloading a4=new Argu_Overloading(34.456f);
[Link]("----------------------------------------------------");
11
| Java Polymorphism |
// calling 1-argument constructor
Argu_Overloading a5=new Argu_Overloading(39);
[Link]("----------------------------------------------------");
}
}
2. OUTPUT
12
| Java Polymorphism |
II. RUN TIME POLYMORPHISM
• Same method (single method) performs different operations using
same set of signatures
• Signatures Number of arguments, Type of arguments
• This is called using its signatures
• Ex.
1. Method Overriding.
Existing Problem
• If variables or methods or combination of both are defined in both
super class and sub class, then compiler may confuse to call the
methods. (This situation is called as ambiguity error)
• So only the methods of derived class will be executed forever and
super class methods will be hidden
• In order to call the members of base class (super class), we have to
use super keyword
Solutions for Run time polymorphism
• In the run time polymorphism, the sub class (derived class) always
hides the base class functions / variables, because of same signatures
• To overcome this problem, java provides one solution. Namely
1. Method Overriding.
METHOD OVERRIDING
• If a same method (single method) performs different operations with
same set of signatures, then it is called as method overriding.
• Unlike C++, java doesn’t use the virtual keyword in super class.
Because methods in java are virtual by default. So, no need to mention
the virtual keyword in super class.
Problem
• Whenever variables and methods are defined with same name in both
super class and sub class, that time JVM will call only sub class
members and hiding the members of super class
• This is the main drawback.
13
| Java Polymorphism |
Solutions
1. Use the super keyword to access the super class members.
2. Use up casting approach to call both methods of super and sub class
using super class object
1. Method Overriding using Super Keyword (Solution 1)
• The super keyword is used to access the variables, methods and
constructors of the super class that has the same name in the sub
class.
• Unlike this(), the super() expression can be placed at anywhere (first
statement or last statement) in the method of sub class
• It is important to note that, here both variables and methods of
super class can be overridden.
Method Overriding using Up Casting (Solution 2
• It is possible to call the sub class (derived class) methods using super
class object
• This is similar to c++ virtual function. Java does not support pointers. It
uses reference instead of pointer
• Process of assigning the object of sub class (derived class) to super
class object variable. Once object is assigned, then super class object
can call the methods of sub class (derived class)
• Here only methods of super class can be overridden. Variables of
super class can’t be overridden in sub class (derived class)
Heap Memory
Object of super Object of sub
class class
Figure: Up casting
14
| Java Polymorphism |
Overriding Rules
• This applies ONLY to inherited methods related to polymorphism
• Overriding methods must have the same argument list and same
return types
• Abstract method must be overridden
• Final methods cannot be overridden
• Static methods cannot be overridden
• Constructors cannot be overridden.
V. TRADITIONAL OVERIDDING IN INHERITANCE
([Link])
1. SOURCE CODE
// super class
class A
{
int k=99;
void test() Super Class
{
[Link]("Class A is calling...");
[Link]("k= "+k);
}
}
// inherit the properties super class A
class B extends A
{
int k=248;
Derived Class
void test()
{
[Link]("Class B is calling...");
[Link]("k= "+k);
}
15
| Java Polymorphism |
}
// main class
public class Traditional
{
public static void main(String[] args)
{
[Link]("===============================");
[Link]("\tTraditional Method Overriding ");
[Link]("===============================");
// create an object for sub class
B obj=new B();
// call the methods of super & sub classes using sub class object
[Link]();
[Link]();
}
}
16
| Java Polymorphism |
2. OUTPUT
17
| Java Polymorphism |
VI. SOLVING METHOD OVERIDDING
(THROUGH INHERITANCE USING SUPER KEYWORD)
([Link])
Used Inheritance : Single Inheritance
1. SOURCE CODE
// super class
class A
{
int k=99;
void test()
{
[Link]("Class A is calling...");
[Link]("k= "+k);
}
}
// Inherit the properties of super class A
class B extends A
{ The super calling can be placed
anywhere in the derived class method
int k=248;
void test()
{
[Link](); // call the super class method
[Link]("Class B is calling...");
[Link]("k= "+k);
}
18
| Java Polymorphism |
}
// main class
public class Traditional
{
// main method
public static void main(String[] args)
{
[Link]("==============================");
[Link]("\tMethod Overriding Concept");
[Link]("==============================");
// create an object for sub class
B obj=new B();
// call the methods of super & sub classes using sub class object
[Link]();
}
}
19
| Java Polymorphism |
2. OUTPUT
20
| Java Polymorphism |
VII. SOLVING METHOD OVERIDDING
(THROUGH INHERITANCE USING UP CASTING)
([Link])
Used Inheritance : Single Inheritance
1. SOURCE CODE
// super class
class S
{ Up Casting
int i=25; Super class variable cannot be
overridden in sub class.
void disp()
{
[Link]("Super class is calling ...");
}
}
// sub class
public class N extends S
{
Up Casting
int i=50; Super class method can be
void disp() overridden in sub class.
{
[Link]("Sub class is calling ...");
}
public static void main(String[] args)
{
[Link]("========================");
21
| Java Polymorphism |
[Link]("\tOveridding through Up Casting");
[Link]("========================");
// object creation for super class
S obj=new S();
[Link]("i= "+obj.i);
// calling super class method using super class object
[Link]();
// object creation for sub class
N sub=new N();
// UP CASTING: ASSIGNING SUB CLASS OBJECT TO SUPER CLASS
obj=sub;
// calling sub class method using super class object
[Link]();
[Link]("i= "+obj.i);
}
}
22
| Java Polymorphism |
2. OUTPUT
23
| Java Polymorphism |
VII. OVERIDDING THROUGH INTERFACE
([Link])
Used Inheritance : Hierarchical Inheritance
1. SOURCE CODE
// super interface
interface Shape Super Interface
{
void area(int v); // empty method
}
// sub class 1
class Square implements Shape
{
Sub Class 1
public void area(int a)
{
int rs=a*a;
[Link]("Area of the Square : "+rs);
}
}
// sub class 2
class Circle implements Shape
{
final float PI=3.14f;
Sub Class 2
public void area(int r)
{
float rs=PI*r*r;
[Link]("Area of the Circle : "+rs);
}
}
24
| Java Polymorphism |
// main class
public class Ioverloadding
{
public static void main(String[] args)
{
[Link]("================================");
[Link]("\tOverriding via Interfaces");
[Link]("================================");
// create an object for square sub class
Square sq=new Square();
[Link](5);
// create an object for circle class
Circle cr=new Circle();
[Link](10);
}
}
25
| Java Polymorphism |
2. OUTPUT
26