POLYMORPHISM
Introduction
• Polymorphism is the ability of an object to take on many forms.
• In other words, polymorphism allows us to define one interface
and have multiple implementations.
• Polymorphism just means that, basically, once we have got a child
class, we can use objects of that child class wherever we would
use objects of the parent class. Java will automatically invoke the
right methods.
Introduction
So polymorphism can be elaborated as:
• It is a feature that allows one interface to be used for a general class
of actions.
• An operation may exhibit different behaviour in different instances.
• The behaviour depends on the types of data used in the operation.
• It plays an important role in allowing objects having different
internal structures to share the same external interface.
• Polymorphism is extensively used in implementing inheritance.
class Fruit {
public void show() {
System.out.println("Fruit");
}
}
class Banana extends Fruit {
//method overriden
public void show() {
System.out.println("Banana");
}
public void makeBananaTree() {
System.out.println("Making a tree");
}
}
public class Application {
public static void main(String[] args) {
Fruit banana = new Banana();
banana.show();
// The following WILL NOT work;
// Variables of type Fruit know only about Fruit methods.
banana.makeBananaTree();
}
} OUTPUT:
Banana
Introduction
class Shape { void draw() { } }
class Circle extends Shape {
private int x, y, r;
Circle(int x, int y, int r) { this.x = x; this.y = y; this.r = r; }
void draw() { System.out.println("Drawing circle (" + x + ", "+ y + ", " + r + ")"); }
}
class Rectangle extends Shape {
private int x, y, w, h;
Rectangle(int x, int y, int w, int h) { this.x = x; this.y = y; this.w = w; this.h = h; }
void draw() { System.out.println("Drawing rectangle (" + x + ", "+ y + ", " + w + "," + h + ")"); }
}
class ShapesMain {
public static void main(String[] args) {
Shape[] shapes = { new Circle(10, 20, 30),
new Rectangle(20, 30, 40, 50) };
for (int i = 0; i < shapes.length; i++)
shapes[i].draw();
}
}
Introduction
Types of Polymorphism in JAVA
Polymorphism
Method
Overloading
Method
Overriding
• In Java, it is possible to define two or more methods of same
name in a class, provided that there argument list or parameters
are different. This concept is known as Method Overloading.
Argument lists could differ in –
• Number of parameters.
• Data type of parameters.
• Sequence of Data type of parameters.
Method Overloading (Compile-time
Polymorphism or Static Polymorphism)
Example 1: Overloading – Different Number of parameters in argument list
When methods name are same but number of arguments are different.
class DisplayOverloading {
public void disp(char c) {
System.out.println(c);
}
public void disp(char c, int num) {
System.out.println(c + " "+num);
}
}
class Sample {
public static void main(String args[]) {
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}
Output:
a
a 10
Method Overloading (Compile-time
Polymorphism or Static Polymorphism)
Example 2: Overloading – Difference in data type of arguments
In this example, method disp() is overloaded based on the data type, one with char
argument and another with int argument.
class DisplayOverloading2{
public void disp(char c) {
System.out.println(c);
}
public void disp(int c) {
System.out.println(c);
}
}
class Sample2{
public static void main(String args[]) {
DisplayOverloading2 obj = new DisplayOverloading2();
obj.disp('a');
obj.disp(5);
}
}
Output:
a
5
Method Overloading (Compile-time
Polymorphism or Static Polymorphism)
Method Overloading (Compile-time
Polymorphism or Static Polymorphism)
Example3: Overloading – Sequence of data type of arguments
Here method disp() is overloaded based on sequence of data type of arguments
class DisplayOverloading3 {
public void disp(char c, int num) {
System.out.println("I’m the first definition of method disp");
}
public void disp(int num, char c) {
System.out.println("I’m the second definition of method disp" );
}
}
class Sample3{
public static void main(String args[]) {
DisplayOverloading3 obj = new DisplayOverloading3();
obj.disp('x', 51 );
obj.disp(52, 'y');
}
}
Output:
I’m the first definition of method disp
I’m the second definition of method disp
Lets see few Valid/invalid cases of method
overloading
Case 1:
int mymethod(int a, int b, float c)
int mymethod(int var1, int var2, float var3)
Result: Compile time error. Argument lists are exactly same. Both methods are having
same number, data types and same sequence of data types in arguments.
Case 2:
int mymethod(int a, int b)
int mymethod(float var1, float var2)
Result: Perfectly fine. Valid case for overloading. Here data types of arguments are
different.
Case 3:
int mymethod(int a, int b)
int mymethod(int num)
Result: Perfectly fine. Valid case for overloading. Here number of arguments are
different.
Lets see few Valid/invalid cases of method
overloading
Case 4:
float mymethod(int a, float b)
float mymethod(float var1, int var2)
Result: Perfectly fine. Valid case for overloading. Sequence of the data types are
different, first method is having (int, float) and second is having (float, int).
Case 5:
int mymethod(int a, int b)
float mymethod(int var1, int var2)
Result: Compile time error. Argument lists are exactly same. Even though return type of
methods are different, it is not a valid case. Since return type of method doesn’t matter
while overloading a method.
1. Overloaded method should always be the part of the same class
(can also take place in sub class), with same name but different
parameters.
2. Constructor in Java can be overloaded
3. Overloaded methods must have a different argument list.
4. The parameters may differ in their type or number, or in both.
5. They may have the same or different return types.
Rules for Method Overloading
Guess the answers before checking it at the end
of programs
Question 1 – return type, method name and argument list same.
class Demo {
public int myMethod(int num1, int num2){
System.out.println("First myMethod of class Demo");
return num1+num2;
}
public int myMethod(int var1, int var2) {
System.out.println("Second myMethod of class Demo");
return var1-var2;
}
}
class Sample4 {
public static void main(String args[]) {
Demo obj1= new Demo();
obj1.myMethod(10,10);
obj1.myMethod(20,12);
}
}
Answer: It will throw a
compilation error: More than
one method with same name
and argument list cannot be
defined in a same class.
Question 2 – return type is different. Method name & argument list same.
class Demo2 {
public double myMethod(int num1, int num2) {
System.out.println("First myMethod of class Demo");
return num1+num2;
}
public int myMethod(int var1, int var2) {
System.out.println("Second myMethod of class Demo");
return var1-var2;
}
}
class Sample5 {
public static void main(String args[])
{
Demo2 obj2= new Demo2();
obj2.myMethod(10,10);
obj2.myMethod(20,12);
}
}
Guess the answers before checking it at the end
of programs
Answer: It will throw a
compilation error: More than one
method with same name and
argument list cannot be given in a
class even though their return
type is different. Method return
type doesn’t matter in case of
overloading.
• Declaring a method in subclass which is already present in
parent class is known as method overriding.
• The benefit of overriding is: ability to define a behaviour that's
specific to the subclass type which means a subclass can
implement a parent class method based on its requirement.
• In object-oriented terms, overriding means to override the
functionality of an existing method.
Method Overriding (Runtime Polymorphism or
Dynamic Polymorphism )
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
}
}
Method Overriding (Runtime Polymorphism or
Dynamic Polymorphism )
Output:
Animals can move
Dogs can walk and run
Consider the following example :
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and run");
}
public void bark(){
System.out.println("Dogs can bark");
}
}
public class TestDog{
public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
b.bark();
}
}
Method Overriding (Runtime Polymorphism or
Dynamic Polymorphism )
Consider the following example :
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and run");
}
public void bark(){
System.out.println("Dogs can bark");
}
}
public class TestDog{
public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
b.bark();
}
}
Method Overriding (Runtime Polymorphism or
Dynamic Polymorphism )
This would produce the following result:
TestDog.java:30: cannot find symbol
symbol : method bark()
location: class Animal
b.bark();
^
This program will throw a compile time error since b's
reference type Animal doesn't have a bark method.
1. Applies only to inherited methods
2. Object type (NOT reference variable type) determines which
overridden method will be used at runtime
3. Overriding method can have different return type
4. Static and final methods cannot be overridden
5. Constructors cannot be overridden
6. It is also known as Runtime polymorphism.
Rules for Method Overriding

Polymorphism.pptx

  • 1.
  • 2.
    Introduction • Polymorphism isthe ability of an object to take on many forms. • In other words, polymorphism allows us to define one interface and have multiple implementations. • Polymorphism just means that, basically, once we have got a child class, we can use objects of that child class wherever we would use objects of the parent class. Java will automatically invoke the right methods.
  • 3.
    Introduction So polymorphism canbe elaborated as: • It is a feature that allows one interface to be used for a general class of actions. • An operation may exhibit different behaviour in different instances. • The behaviour depends on the types of data used in the operation. • It plays an important role in allowing objects having different internal structures to share the same external interface. • Polymorphism is extensively used in implementing inheritance.
  • 4.
    class Fruit { publicvoid show() { System.out.println("Fruit"); } } class Banana extends Fruit { //method overriden public void show() { System.out.println("Banana"); } public void makeBananaTree() { System.out.println("Making a tree"); } } public class Application { public static void main(String[] args) { Fruit banana = new Banana(); banana.show(); // The following WILL NOT work; // Variables of type Fruit know only about Fruit methods. banana.makeBananaTree(); } } OUTPUT: Banana Introduction
  • 5.
    class Shape {void draw() { } } class Circle extends Shape { private int x, y, r; Circle(int x, int y, int r) { this.x = x; this.y = y; this.r = r; } void draw() { System.out.println("Drawing circle (" + x + ", "+ y + ", " + r + ")"); } } class Rectangle extends Shape { private int x, y, w, h; Rectangle(int x, int y, int w, int h) { this.x = x; this.y = y; this.w = w; this.h = h; } void draw() { System.out.println("Drawing rectangle (" + x + ", "+ y + ", " + w + "," + h + ")"); } } class ShapesMain { public static void main(String[] args) { Shape[] shapes = { new Circle(10, 20, 30), new Rectangle(20, 30, 40, 50) }; for (int i = 0; i < shapes.length; i++) shapes[i].draw(); } } Introduction
  • 6.
    Types of Polymorphismin JAVA Polymorphism Method Overloading Method Overriding
  • 7.
    • In Java,it is possible to define two or more methods of same name in a class, provided that there argument list or parameters are different. This concept is known as Method Overloading. Argument lists could differ in – • Number of parameters. • Data type of parameters. • Sequence of Data type of parameters. Method Overloading (Compile-time Polymorphism or Static Polymorphism)
  • 8.
    Example 1: Overloading– Different Number of parameters in argument list When methods name are same but number of arguments are different. class DisplayOverloading { public void disp(char c) { System.out.println(c); } public void disp(char c, int num) { System.out.println(c + " "+num); } } class Sample { public static void main(String args[]) { DisplayOverloading obj = new DisplayOverloading(); obj.disp('a'); obj.disp('a',10); } } Output: a a 10 Method Overloading (Compile-time Polymorphism or Static Polymorphism)
  • 9.
    Example 2: Overloading– Difference in data type of arguments In this example, method disp() is overloaded based on the data type, one with char argument and another with int argument. class DisplayOverloading2{ public void disp(char c) { System.out.println(c); } public void disp(int c) { System.out.println(c); } } class Sample2{ public static void main(String args[]) { DisplayOverloading2 obj = new DisplayOverloading2(); obj.disp('a'); obj.disp(5); } } Output: a 5 Method Overloading (Compile-time Polymorphism or Static Polymorphism)
  • 10.
    Method Overloading (Compile-time Polymorphismor Static Polymorphism) Example3: Overloading – Sequence of data type of arguments Here method disp() is overloaded based on sequence of data type of arguments class DisplayOverloading3 { public void disp(char c, int num) { System.out.println("I’m the first definition of method disp"); } public void disp(int num, char c) { System.out.println("I’m the second definition of method disp" ); } } class Sample3{ public static void main(String args[]) { DisplayOverloading3 obj = new DisplayOverloading3(); obj.disp('x', 51 ); obj.disp(52, 'y'); } } Output: I’m the first definition of method disp I’m the second definition of method disp
  • 11.
    Lets see fewValid/invalid cases of method overloading Case 1: int mymethod(int a, int b, float c) int mymethod(int var1, int var2, float var3) Result: Compile time error. Argument lists are exactly same. Both methods are having same number, data types and same sequence of data types in arguments. Case 2: int mymethod(int a, int b) int mymethod(float var1, float var2) Result: Perfectly fine. Valid case for overloading. Here data types of arguments are different. Case 3: int mymethod(int a, int b) int mymethod(int num) Result: Perfectly fine. Valid case for overloading. Here number of arguments are different.
  • 12.
    Lets see fewValid/invalid cases of method overloading Case 4: float mymethod(int a, float b) float mymethod(float var1, int var2) Result: Perfectly fine. Valid case for overloading. Sequence of the data types are different, first method is having (int, float) and second is having (float, int). Case 5: int mymethod(int a, int b) float mymethod(int var1, int var2) Result: Compile time error. Argument lists are exactly same. Even though return type of methods are different, it is not a valid case. Since return type of method doesn’t matter while overloading a method.
  • 13.
    1. Overloaded methodshould always be the part of the same class (can also take place in sub class), with same name but different parameters. 2. Constructor in Java can be overloaded 3. Overloaded methods must have a different argument list. 4. The parameters may differ in their type or number, or in both. 5. They may have the same or different return types. Rules for Method Overloading
  • 14.
    Guess the answersbefore checking it at the end of programs Question 1 – return type, method name and argument list same. class Demo { public int myMethod(int num1, int num2){ System.out.println("First myMethod of class Demo"); return num1+num2; } public int myMethod(int var1, int var2) { System.out.println("Second myMethod of class Demo"); return var1-var2; } } class Sample4 { public static void main(String args[]) { Demo obj1= new Demo(); obj1.myMethod(10,10); obj1.myMethod(20,12); } } Answer: It will throw a compilation error: More than one method with same name and argument list cannot be defined in a same class.
  • 15.
    Question 2 –return type is different. Method name & argument list same. class Demo2 { public double myMethod(int num1, int num2) { System.out.println("First myMethod of class Demo"); return num1+num2; } public int myMethod(int var1, int var2) { System.out.println("Second myMethod of class Demo"); return var1-var2; } } class Sample5 { public static void main(String args[]) { Demo2 obj2= new Demo2(); obj2.myMethod(10,10); obj2.myMethod(20,12); } } Guess the answers before checking it at the end of programs Answer: It will throw a compilation error: More than one method with same name and argument list cannot be given in a class even though their return type is different. Method return type doesn’t matter in case of overloading.
  • 16.
    • Declaring amethod in subclass which is already present in parent class is known as method overriding. • The benefit of overriding is: ability to define a behaviour that's specific to the subclass type which means a subclass can implement a parent class method based on its requirement. • In object-oriented terms, overriding means to override the functionality of an existing method. Method Overriding (Runtime Polymorphism or Dynamic Polymorphism )
  • 17.
    class Animal{ public voidmove(){ System.out.println("Animals can move"); } } class Dog extends Animal{ public void move(){ System.out.println("Dogs can walk and run"); } } public class TestDog{ public static void main(String args[]){ Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move();// runs the method in Animal class b.move();//Runs the method in Dog class } } Method Overriding (Runtime Polymorphism or Dynamic Polymorphism ) Output: Animals can move Dogs can walk and run
  • 18.
    Consider the followingexample : class Animal{ public void move(){ System.out.println("Animals can move"); } } class Dog extends Animal{ public void move(){ System.out.println("Dogs can walk and run"); } public void bark(){ System.out.println("Dogs can bark"); } } public class TestDog{ public static void main(String args[]){ Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move();// runs the method in Animal class b.move();//Runs the method in Dog class b.bark(); } } Method Overriding (Runtime Polymorphism or Dynamic Polymorphism )
  • 19.
    Consider the followingexample : class Animal{ public void move(){ System.out.println("Animals can move"); } } class Dog extends Animal{ public void move(){ System.out.println("Dogs can walk and run"); } public void bark(){ System.out.println("Dogs can bark"); } } public class TestDog{ public static void main(String args[]){ Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move();// runs the method in Animal class b.move();//Runs the method in Dog class b.bark(); } } Method Overriding (Runtime Polymorphism or Dynamic Polymorphism ) This would produce the following result: TestDog.java:30: cannot find symbol symbol : method bark() location: class Animal b.bark(); ^ This program will throw a compile time error since b's reference type Animal doesn't have a bark method.
  • 20.
    1. Applies onlyto inherited methods 2. Object type (NOT reference variable type) determines which overridden method will be used at runtime 3. Overriding method can have different return type 4. Static and final methods cannot be overridden 5. Constructors cannot be overridden 6. It is also known as Runtime polymorphism. Rules for Method Overriding