T
Thomas Strandh
When trying to override static methods in Java (1.5.x) you get unexpected
results.
The overriding doesn't work they way you expect.
When running the sample code below you get the following output:
Static overloading: 2 1
Instance overloading: 20 20
I expected this output:
Static overloading: 2 2
Instance overloading: 20 20
My opinion is that this behaviour is a bug.
It violates the fundametals of object oriented programming.
- Can you give me a reason why the JVM treats the overrided static methods
this way?
Code sample follows:
/*
* 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();
}
}
results.
The overriding doesn't work they way you expect.
When running the sample code below you get the following output:
Static overloading: 2 1
Instance overloading: 20 20
I expected this output:
Static overloading: 2 2
Instance overloading: 20 20
My opinion is that this behaviour is a bug.
It violates the fundametals of object oriented programming.
- Can you give me a reason why the JVM treats the overrided static methods
this way?
Code sample follows:
/*
* 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();
}
}