From the docs, "If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass."
I understand the difference between method hiding and overriding. However, it's strange to say that the subclass hides the superclass method because if you have the following:
public class Cat extends Animal {
public static void testClassMethod() {
System.out.println("The static method in Cat");
}
public void testInstanceMethod() {
System.out.println("The instance method in Cat");
}
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = myCat;
Animal.testClassMethod();
myAnimal.testInstanceMethod();
}
}
The superclass's static method is called. But by the definition of hiding, the method in the subclass is hiding the one in the superclass. I don't see how the subclass is "covering up/hiding" the superclass static method, as the superclass's method is the one that's actually called.
When super class and sub class contains same method including parameters and if they are static. The method in the super class will be hidden by the one that is in the sub class. This mechanism is known as method hiding.
1. Method hiding is also known as compile-time polymorphism because the compiler is responsible to resolve method resolution based on the reference type. 2. It is also known as static polymorphism or early binding.
Static methods can not be overridden(Method Overriding vs Method Hiding) : When you define a static method with same signature as a static method in base class, it is known as method hiding. The following table summarizes what happens when you define a method with the same signature as a method in a super-class.
The superclass's static method is called.
Yes. But that is because you explicitly named the superclass's static method by qualifying with the superclass name in the call statement.
If you had written the main
like this instead:
public static void main(String[] args) {
...
testClassMethod();
}
then you would have seen that the Cat
version of testClassMethod
was called. Here, the Cat.testClassMethod
method hides the Animal.testClassMethod
method
Cat
's testClassMethod()
hides Animal.testClassMethod()
, since if you didn't have a static testClassMethod()
in the Cat
class, Cat.testClassMethod()
would invoke Animal.testClassMethod()
.
When you call Animal.testClassMethod()
, it's can't be hidden by a sub-class's method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With