Monday, 3 August 2015

Polymorphism works for static ??

No, polymorphism will not work at all for static methods. Method will be executed based on the type of the reference type not on the type of type of object pointed to.

Please find the example below.


public class StaticTest
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
       
        BaseClass bc = new SubClass();
        bc.method1();
    }
}


class BaseClass{

public static void method1(){

System.out.println("Base class");

}
}

class SubClass extends BaseClass{

public static void method1(){

System.out.println("Sub class");

}
}


Output:  Hello World!
                Base class

No comments:

Post a Comment