Polymorphism in Java


Polymorphism in Java
Polymorphism means, existence of Object behavior in many forms

There are two types of Polymorphism

i) Compile Time Polymorphism / Static binding / Method overloading

ii) Run Time Polymorphism / Dynamic binding / Method overriding
------------------------------------------
i) Compile Time Polymorphism 

If two or more methods having same name in the same class but they differ in the following ways.

i) Number of Arguments

ii) Type of Arguments

Example:
public class MethodOverloading {
    public void add(int a, int b){
        System.out.println(a+b);
    }
    public void add(int a, int b, int c){
        System.out.println(a+b+c);
    }
    public void add(double a, double b){
        System.out.println(a+b);
    }
    public void add(double a, double b, double c){
        System.out.println(a+b+c);
    }
    public static void main (String [] args){
        MethodOverloading obj = new MethodOverloading();
        obj.add(10, 20);
        obj.add(10, 20, 30);
        obj.add(1.2345, 2.3456);
        obj.add(1.2345, 2.3456, 4.45678);
    }
}
-----------------------------------------
ii) Run Time Polymorphism 

If two or more methods having same name and same arguments available in the super class and sub class.

Example:

Class 1

public class A {

public void addition(int a, int b) {
    System.out.println(a+b);
}
public static void main (String [] args){
    A myObject = new A();
    myObject.addition(10, 20);//30
}
}
------------------------------
Class 2:
public class B extends A {
    public void addition(int a, int b) {
        System.out.println(a+b);
    }
public static void main (String [] args){
    A obj1 = new A ();
    obj1.addition(10, 20); //30
       
    B obj2 = new B();
    obj2.addition(40, 50);//90
}
}
--------------------------------------------------

0 comments:

Post a Comment