I'm a beginner in Java programming language, and I'm reading the sun tutorial. About inheritance: I understand subclasses can override methods and hide member variables of the superclass. But in the exercises, they talk also about hiding methods. It seems related to static method of the superclass. So, what's about the inheritance of static methods?
Overriding and dynamic binding are closely realted. All non-static methods are dynamically bound. That is, at runtime it is determined which method to call. If a class overrides a non-static method then its method is called , otherwise its ancestor method would be called. Static method calls are bound at compile time and that is why overriding doesn't apply in case of static methods. When a subclass reimplements a static method then it is called method hiding and not method overriding. Let us take an example:
class A {
staticvoid s() { }
void d() { }
}
class B extends A {
staticvoid s() { }
void d() { }
}
When you write:
A a = new B() ;
a.d() ;
then class to a.d() is resolved at run time. Since at runtime a will refer to an object of class B, d() method in class B will be called here.
If you write:
A a = new A() ;
a.d() ;
then d() method in A will be called.
However, if you write:
A a = new B() ;
a.s() ;
then s() method in A will be called. It is so because s() is a static method and at cmpile time a.s() was replaced by A.s() becauase a was a reference variable of A type.
If you write:
A a = new A() ;
a.s() ;
then A.s() will be called again.