Java中隐藏的方法是什么?甚至 JavaDoc 的解释也令人困惑 [英] What is method hiding in Java? Even the JavaDoc explanation is confusing

查看:12
本文介绍了Java中隐藏的方法是什么?甚至 JavaDoc 的解释也令人困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Javadoc 说:

被调用的隐藏方法的版本是超类中的版本,而被调用的覆盖方法的版本是子类中的版本.

the version of the hidden method that gets invoked is the one in the superclass, and the version of the overridden method that gets invoked is the one in the subclass.

没有给我敲响警钟.任何显示此含义的清晰示例都将受到高度赞赏.

doesn't ring a bell to me. Any clear example showing the meaning of this will be highly appreciated.

推荐答案

public class Animal {
    public static void foo() {
        System.out.println("Animal");
    }
}

public class Cat extends Animal {
    public static void foo() {  // hides Animal.foo()
        System.out.println("Cat");
    }
}

这里,Cat.foo() 据说隐藏了 Animal.foo().隐藏不像覆盖那样工作,因为静态方法不是多态的.所以会发生以下情况:

Here, Cat.foo() is said to hide Animal.foo(). Hiding does not work like overriding, because static methods are not polymorphic. So the following will happen:

Animal.foo(); // prints Animal
Cat.foo(); // prints Cat

Animal a = new Animal();
Animal b = new Cat();
Cat c = new Cat();
Animal d = null;

a.foo(); // should not be done. Prints Animal because the declared type of a is Animal
b.foo(); // should not be done. Prints Animal because the declared type of b is Animal
c.foo(); // should not be done. Prints Cat because the declared type of c is Cat
d.foo(); // should not be done. Prints Animal because the declared type of d is Animal

在实例而不是类上调用静态方法是一种非常糟糕的做法,永远不应该这样做.

Calling static methods on instances rather than classes is a very bad practice, and should never be done.

将此与实例方法进行比较,实例方法是多态的,因此会被覆盖.调用的方法取决于对象的具体运行时类型:

Compare this with instance methods, which are polymorphic and are thus overridden. The method called depends on the concrete, runtime type of the object:

public class Animal {
    public void foo() {
        System.out.println("Animal");
    }
}

public class Cat extends Animal {
    public void foo() { // overrides Animal.foo()
        System.out.println("Cat");
    }
}

然后会发生以下情况:

Animal a = new Animal();
Animal b = new Cat();
Cat c = new Cat();
Animal d = null;

a.foo(); // prints Animal
b.foo(); // prints Cat
c.foo(); // prints Cat
d.foo(): // throws NullPointerException

这篇关于Java中隐藏的方法是什么?甚至 JavaDoc 的解释也令人困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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