This is not inheritance. A static member belongs to the class where it is defined.
You can use the class name to reference it. You can use an instance of the class to reference it. In the later case, the compiler replaces the instance's name by the class's name.
The compiler knows that Dog extends Animal. If it cannot find a definition in Dog for the static variable "name", it substitutes Dog for Animal. It will go up the hierarchy tree until it finds a definition or concludes that it is not defined.
As Seetharaman mentioned, static members can be redefined. In which case, the compiler finds the definition right away.
If you look carefully, you will see that static variables and static method behave the same way.
Here is the output of the code above:
Related to Overriding & Overloading,
1) A compilation error occurs if an instance method overrides a static method.
2) A compilation error occurs if a static method hides an instance method.
3) It's possible for a static variable to hide an instance variable.
4) It's also permissible for an instance variable to hide a static variable.
For static methods, the compiler uses the declared type of reference. That's what we mean when we say a static method doesn't have run-time polymorphism, Because instance methods and class methods have this important different in behaviors, we use different terms - "overriding" for instance methods, and "hiding" for class methods.
When we say, you can't override a static method, what that means is even if you write code that looks like it's overriding a static method - it won't behave like an overriden method(no polymorphism)
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Joined: Sep 12, 2009
Thanks Abimaran......Thats what i was asking !!!
I got it now....
But i also observed the same behaviur and wrote as rules.....But do you know the logic behind above rules ???