问题描述
从 docs 中,如果子类定义了一个具有与超类中的静态方法相同签名的静态方法,然后子类中的方法将其隐藏在超类中."
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.
推荐答案
是的.但这是因为您通过在调用语句中使用超类名称进行限定来显式命名超类的静态方法.
Yes. But that is because you explicitly named the superclass's static method by qualifying with the superclass name in the call statement.
如果您是这样写main
的,则:
If you had written the main
like this instead:
public static void main(String[] args) {
...
testClassMethod();
}
然后您会看到调用了testClassMethod
的Cat
版本.在这里,Cat.testClassMethod
方法隐藏了Animal.testClassMethod
方法
then you would have seen that the Cat
version of testClassMethod
was called. Here, the Cat.testClassMethod
method hides the Animal.testClassMethod
method
这篇关于为什么将其称为“方法隐藏"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!