Never talk about statics and overrides in the same sentence.
The whole concept of redefinable methods is to dynamically bind at runtime to be executed. Consider this:
class A { void print() { out.println("A"); } class B extends A { void print() { out.println("B"); } A obj = new B(); obj.print();
Although the variable obj
is of type A
, it still outputs "B".
Static methods, on the other hand, are bound at compile time. This means that the compiler uses the type of the variable (or expression) to determine which method to execute:
class A { static void print() { out.println("A"); } class B extends A { static void print() { out.println("B"); } A obj = new B(); obj.print();
Now it gives "A". Unfortunately, the Java language allows you to call static methods on variables or expressions. This is not recommended! It is better to call static methods for the type itself:
A.print(); B.print();
In the first example, obj.print();
- the compiler automatically translates the operator into A.print()
. The actual object is not taken into account. In fact, you could write the following:
A obj = null; obj.print();
Or:
((A) null).print();
It is still typing "A".
source share