Java Polymorphism | Java example

 

Java Polymorphism :

Polymorphism is one of the concept in OOP in java.The word polymorphism is derived from Greek words poly means many morph means forms and task is done in different types.

 

There are two types of polymorphism in java

 

Compile time polymorphism:

Compile time polymorphism is achieved by method overloading. We create a method display and try to overload it multiple times.

 

class Methods{

void display(){

    System.out.println("Welcome abhi");
}

void display(String name){

    System.out.println("Welcome "+name);
}

void display(String name, String email){

    System.out.println("Welcome "+name+" email "+email);
}

}

 

Now we will access the above methods

public class MethodOverloading {

    public static void main(String args[]) {

        Methods methods = new Methods();

        methods.display();
        methods.display("abhi");
        methods.display("abhi","abhi@email.com");

    }

}

 

java polymorphism

 

Run time polymorphism:

Run time polymorphism is achieved by method overriding.We create a methods and try to override it several times.

 

class Method{

    void display(){

        System.out.println("This is primary method declaration");
    }

}

 

We will create a class MethodOverriding1 and extend it with Method then over ride the display method

 

class MethodOverriding1 extends Method {

    void display(){

        System.out.println("This is MethodOverriding 1 declaration");
    }

}

 

and for the second time we implement the same

class MethodOverriding2 extends Method {

    void display(){

        System.out.println("This is MethodOverriding 2 declaration");
    }

}

 

then finally we will print the methods overridden as

class MethodOverriding extends Method{

    public static void main(String args[]){

        Method m = new MethodOverriding1();

        m.display();

        m = new MethodOverriding2();

        m.display();


    }
}

 

java polymorphism

 

Show Buttons
Hide Buttons
Read previous post:
Java Encapsulation || Java example

  Java Encapsulation : Java encapsulation is a process of wrapping up of data members and member function.Don't get it...

Close