Hello,
There's the statement: Static methods cannot be overriden
This is not quite correct. You can override static methods but
they are hidden:
class Parent {
public static
String getMessage()
{ return "I am the parent"; }
}
class Child extends Parent {
public static String getMessage()
{ return "I am the child"; }
}
public class Test2{
public static void main( String [] args ) {
Parent p = new Parent();
Child c = new Child();
System.out.println( p.getMessage() );
System.out.println( c.getMessage() );
Parent p2 = c; // upcast the child
System.out.println( p2.getMessage() );
// if overriding works,
you should still
// see "I am the child."
}
}
if overriding works, you should still see "I am the child."
Result:
I am the parent
I am the child
I am the parent => No dynamic binding for static methods
This is because static methodes have compile time binding.
This means if they are changed during runtime by cast there
is no dynamic binding => Instead of "I am the child"
"I am the parent will be printed".
If there would be a dynamic binding as for non static/non final
methods => I am the child
Question:
An upcast of an object with a static method works. Why is there
a RUNTIME-Error if I do a downcast:
class Parent {
public static String getMessage()
{ return "I am the parent"; }
}
class Child extends Parent {
public static String getMessage()
{ return "I am the child"; }
}
public class Test2b{
public static void main( String [] args ) {
Parent p = new Parent();
Child c = new Child();
System.out.println( p.getMessage() );
System.out.println( c.getMessage() );
// Parent p2 = c; // upcast the child
Child c2 = (Child) p; // Now downcast the Parent
// System.out.println( p2.getMessage() );
System.out.println( c2.getMessage() );
}
}
------------------