Overriding and Redefining (also known as hiding) are almost the some thing except:
Overriding is for instance methods and Redefining or hiding is for Class methods. Redefining is only in case of Static methods as Static methods don't have a run time Polymorphism.
Please refer to the below code for clarification:
class Foo {
public static void classMethod()
SOP("classMethod() in Foo");
}
public void instanceMethod()
{
SOP ("instanceMethod() in Foo");
}
}
class Bar extends Foo {
public static void classMethod()
{
SOP ("classMethod() in Bar");
}
public void instanceMethod() {
SOP ("instanceMethod() in Bar");
}
}
class Test {
public static void main(String[] args) {
Foo f = new Bar();
f.instanceMethod();
f.classMethod();
}
}
The Output for this code is:
instanceMethod() in Bar
classMethod() in Foo
Reason for this Output:
Since instanceMethod () is an instance method, in which Bar overrides the method from Foo, at run time the J.V.M. uses the actual class of the instance f to determine which method to run. Although f was declared as a Foo, the actual instance we created was a new Bar(). So at run time, the J.V.M. finds that f is a Bar instance, and so it calls instanceMethod () in Bar rather than the one in Foo.
With classMethod () , as it's a class method, the compiler and J.V.M. don't expect to need an actual instance to invoke the method. And even if you provide one the J.V.M. will never look at it. The compiler will only look at the declared type of the reference, and use that declared type to determine, at compile time, which method to call. Since f is declared as type Foo, the compiler looks at f.classMethod() and decides it means Foo. class Method. It doesn't matter that the instance referred to by f is actually a Bar - for static methods, the compiler only uses the declared type of the reference.
That's why I said in the beginning that a static method does not have run-time polymorphism.