Method overriding is a polymorphic behavior where actual object is identified at run time and subsequent method from that object is invoked. on the other hand Static methods are resolved and bind during compile time instead of run time and type of variable is used for that. that's why even if you override static method , the actual method would be invoked depends upon type of variable.
just like in this example , type of array is Animal even though there are Dog object on it but since method is static it was bind with Animal at run time and that's why the output as a a a
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!