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

查看:357
本文介绍了隐藏在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();
Animal 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天全站免登陆