From question three in these OCA practice questions (pdf):
abstract class Writer {
public static void write() {
System.out.println("Writing...");
}
}
class Author extends Writer {
public static void write() {
System.out.println("Writing book");
}
}
public class Programmer extends Writer {
public static void write() {
System.out.println("Writing code");
}
public static void main(String[] args) {
Writer w = new Programmer();
w.write();
}
}
The output is Writing...
.
I don't understand why. As Programmer
overrides Writer
's write method, I thought it should call the method in Programmer
and not in Writer
.
Why?
You have to understand two points here.
There is no overriding concept in case of static
members. They are simply static
and never change based on instance.
And static
members bind to class rather than instance. So no matter what is the instance, they look the type they got called and execute.