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

标签 java oop method-hiding

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/

相关文章:

java - 浪费内存来加速jvm

java - 多模块 Maven 项目中的 Axis2 Web 服务

java - 在java中打印MySql结果集

oop - 将静态方法作为参数传递给 Kotlin 中的另一个方法

java - docs.oracle.com 上有关覆盖和隐藏方法的文本是否含糊不清?

c++ - 清除函数隐藏 C++ 中的编译器警告

java - Swing 组件中的 HTML 格式文本不显示

java - (Java新手)实例化未知数量的对象

java - 装饰器模式 : Why do we need an abstract decorator?

c# - 在返回派生类型的派生接口(interface)中隐藏属性是否可以接受?