Total Pageviews

Sunday, January 30, 2011

Static Method are always resolved during Compile Time


Consider the following snippet of code :


class SuperClass{

public static void staticMethod(){

System.out.println("SuperClass: inside staticMethod");

}

}


public class SubClass extends SuperClass{

public static void staticMethod(){

System.out.println("SubClass: inside staticMethod");

}


public static void main(String []args){

SuperClass superClassWithSuperCons = new SuperClass();

SuperClass superClassWithSubCons = new SubClass();

SubClass subClassWithSubCons = new SubClass();


superClassWithSuperCons.staticMethod();

superClassWithSubCons.staticMethod();

subClassWithSubCons.staticMethod();

}


}






It will be interesting to note that the output will be


SuperClass: inside staticMethod

SuperClass: inside staticMethod

SubClass: inside staticMethod



Overriding in Java simply means that the particular method would be called based on the run time type of the object and not on the compile time type of it (which is the case with overriden static methods). Okay... Because they are class methods and hence access to them is always resolved during compile time only using the compile time type information.


we're invoking the staticMethod() on an object of Runtime Type as SubClass and not as SuperClass. This confirms that the static methods are always resolved using their compile time type information only Since at compile time first two of the objects contains references to the SuperClass only.





1 comment:

  1. Can you please explain what this statement actually means ?
    SuperClass superClassWithSubCons = new SubClass(); ... It would be a great help if you explain it with pointers and references.

    ReplyDelete