gpt4 book ai didi

java - Java中隐藏的方法是什么?甚至 JavaDoc 的解释也令人困惑

转载 作者:IT老高 更新时间:2023-10-28 20:22:26 25 4
gpt4 key购买 nike

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.

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

最佳答案

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()。隐藏不像覆盖那样起作用,因为静态方法不是多态的。所以会发生以下情况:

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

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

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

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 - Java中隐藏的方法是什么?甚至 JavaDoc 的解释也令人困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16313649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com