Rohit Sidana wrote:Hi...everyone....Today i was reading my book where i got one statement that " Static methods can't be overridden but can be redefined."
Can anyone please explain me this statement that what is the difference between redefine a code and override the code?
and the output of this code is :
a a a
The difference between redefinition and overriding is simple. When you override a method, at runtime the object determines which method will execute. Redefining a static method means that the reference variable determines which method will execute.
Here is some code that will make it easier to grasp:
In the above example class Dog has two methods do() and eat(). They are neither overridden nor redefined. Now, imagine you want the static do() method to print DOG. You would want to re-define the method (un-comment Line 1 above). Here is tricky part: Consider this...
What happens when the compiler sees Line 2 and Line 3 above? It substitutes the reference variable "a" and the reference variable "d" with the CLASS NAME! So the compiler sees Animal.do(); and prints ANIMAL and also the compiler sees Dog.do(); and prints DOG.
Let me get back to LINE 2 above. if this method was not static the object would determine the invoked method, so a.do() would have printed DOG. But with static methods the compiler substitutes the reference variable with the class name (via ClassLoader) and invokes that same CLASS-specific method.
This is why you can only redefine static methods, for example, if you wanted the static animal do() to print something else rather than "ANIMAL"
Hope this answered your question!