Java Polymorphism

Polymorphism means having more than one forms. You will learn about it in three chapters namely Method Overloading, Constructor Overloading, and Method Overriding

Types of Polymorphism

There are the following two types of polymorphism available in Java:

Java Polymorphism Example

Here is an example program, helps in understanding the polymorphism in Java:

/* Java Polymorphism - Example Program */

class MyClassA
{
    void myMethod()
    {
        System.out.println("Inside MyClassA's myMethod method");
    }
}
class MyClassB extends MyClassA
{
    void myMethod()
    {
        System.out.println("Inside MyClassB's myMethod method");
    }
}
class MyClassC extends MyClassA
{
    void myMethod()
    {
        System.out.println("Inside MyClassC's myMethod method");
    }
}

class JavaPolymorphismTest
{
    public static void main(String args[])
    {
        MyClassA Aob = new MyClassA();  // object of type MyClassA
        MyClassB Bob = new MyClassB();  // object of type MyClassB
        MyClassC Cob = new MyClassC();  // object of type MyClassC
        
        MyClassA ref;   // obtained a reference of type MyClassA
        
        ref = Aob;      // ref refers to a MyClassA object
        ref.myMethod(); // calls MyClassA's version of myMethod()
        
        ref = Bob;      // ref refers to a MyClassB object
        ref.myMethod(); // calls MyClassB's version of myMethod()
        
        ref = Cob;      // ref refers to a MyClassC object
        ref.myMethod(); // calls MyClassC's version of myMethod()
    }
}

Here is the sample output produced by the above Java program:

Inside MyClassA's myMethod method
Inside MyClassB's myMethod method
Inside MyClassC's myMethod method

Java Online Test


« Previous Tutorial Next Tutorial »