为什么将其称为“方法隐藏"? [英] Why is it called "method hiding"?

查看:122
本文介绍了为什么将其称为“方法隐藏"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

推荐答案

超类的静态方法被调用.

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.

如果您是这样写main的,则:

If you had written the main like this instead:

public static void main(String[] args) {
    ...
    testClassMethod();
}

然后您会看到调用了testClassMethodCat版本.在这里,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

这篇关于为什么将其称为“方法隐藏"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆