Ramya Subraamanian wrote:line 13 must call the sub class's static method but instead the super class method is called. so overriding doesnt work here..
so if i get a question static methods can be overridden - true or false. would the answer be False ?
Only inherited
instance methods can be overridden! Static (class) methods are
never overridden. Never! Repeat after me:
static (class) methods are
never overridden
But as your code snippet illustrates, a subclass can define a
static method with the same signature as a
static method in the superclass. That's called
hiding: the method in the subclass hides the one in the superclass. Did you know the rules for method overriding apply to these hiding
static methods as well, although they can't be overridden? Read
this post to find out more. So if you change the access modifier or the return type of
staticMethod() in class
Cow3, you'll get a compiler error.
The big difference between method overriding (instance methods) and method hiding (class/static methods) is which version of the method is executed (as you discovered as well in your code snippet):
1/ with hidden static methods, the static method of the reference type will be executed. So that's why
prints
Mammal1 staticMethod. The reference type of
mammalClassWithSubCons is
Mammal1 and therefore its
staticMethod() is executed. It doesn't matter that
mammalClassWithSubCons refers to a
Cow3 instance.
2/ with overridden instance methods, the instance method of the actual object (to which the reference variable is refering) will be executed.
Hope it helps!
Kind regards,
Roel