Runtime Polymorphism in Java

Polymorphism means ability to take more than one form. In RunTime Polimorphism resolution to call to method is determined at runtime rather than compile time.
  • Method are overriden but data member are not so runtime polymorphism is not applied to data members

Java Prograam to explain Runtime Polymorphism
package com.anuj.basic;
/**
 * 
 * @author Anuj
 */
class A{
    int i=10;
    
    public void print(){
        System.out.println("A Print Called");
    }
    public void printMessage(){
        System.out.println("printMessage of Class A Called");
    }
}

/**
 * 
 * @author Anuj
 */
class B extends A{
    int i=20;
    public void print(){
        System.out.println("B Print Called");
    }
    public void printMessage(A a){
        System.out.println("printMessage of Class B Called");
    }    
}

/**
 * 
 * @author Anuj
 */
class C extends B{
    int i=20;
}

/**
 *
 * @author Anuj
 * source : golenpackagebyanuj.blogspot.com
 */
public class PolyMorphism {
       
    public static void main(String[] args) {
        A a = new B();
        
        //Compiler check and validates that method print exist in class A or not.
        //At Runtime identifies that a is references to Class B. So Print of Class B is called.
        a.print();
        
        //Method is overriden but data member is not. so Runtime polimorphism can't be achieved by data member
        //print value of i of Class A
        System.out.println(a.i);
        
        a = new C();
        //Compiler check and validate of print is present in class A or not.
        //At runtime it identifies that a is references of Class C but c doesn't have method but it extends B and B has same method.
        //So print of Class B is called.
        a.print();
        
        //Compiler check and validates that method printMessage with Argument exist in class A or not.
        //it complains at compile time.
        a = new B();
        a.printMessage(a);
        
        //B b = new A() complains at compile time since A can not be converted to B
        //So new A() needs to be casted to B so compiler will not complain
        //B b = (B)new A();
        //Exception at runtime that A Can't be cast to B.
        //b.print();
    }
}

Output :
run:
B Print Called
10
B Print Called
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: com.anuj.basic.A.printMessage
at com.anuj.basic.PolyMorphism.main(PolyMorphism.java:67)
Java Result: 1

No comments:

Post a Comment