Collection of references and notes on Java and J2EE

Friday, March 23, 2007

Java: Static methods are not overriden

In Java, sub-class static method can have same signature as super-class static method. But it does not mean that super-class static method is overridden by sub-class static method. Look at the following code (from reference)
-------------------------------------------
/*

* SubClass.java

*

* Created on den 23 juni 2005, 21:13

*/

package sample;

/**

*

* @author Thomas

*/

public class SubClass extends SuperClass{

public static Long getStaticLongId(){

return 2L;

}

public Long getInstanceLongId(){

return 20L;

}

public static final void main(String args[]){

SubClass subClassInstance = new SubClass();

System.out.println("Static overloading:\t" +

SubClass.getStaticLongId() + "\t" +

SubClass.getStaticStringId());

System.out.println("Instance overloading:\t"+

subClassInstance.getInstanceLongId() + "\t" +

subClassInstance.getInstanceStringId());

}

}

/*

* SuperClass.java

*

* Created on den 23 juni 2005, 21:09

*/

package sample;

/**

*

* @author Thomas

*/

public class SuperClass {

public static Long getStaticLongId(){

return 1L;

}

public static String getStaticStringId(){

return getStaticLongId().toString();

}

public Long getInstanceLongId(){

return 10L;

}

public String getInstanceStringId(){

return getInstanceLongId().toString();

}
}
------------------------------------------------------

Output will be -
Static overloading: 2 1
Instance overloading: 20 20

For detailed reason about it, look at the reference.

As a side-note, if you put this code in eclipse, you will see little triangle by the side of overridden instance method "getInstanceLongId()". This sign will be missing for static method "getStaticLongId()".

Reference:
* Overriding static methods - why doesn´t it work?

4 comments:

Anonymous said...

Yes, this is known.

Eugene Kaganovich said...

If I interview anyone who doesn't know this, they don't get the job.

Mantasha said...
This post has been removed by a blog administrator.
Mantasha said...
This post has been removed by a blog administrator.