Javadoc says:
调用的隐藏方法的版本是超类中的版本,调用的重写方法的版本是子类中的版本。
没有给我敲响警钟。任何显示其含义的清晰示例都将受到高度赞赏。
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");
}
}
Here, 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)