java非静态到静态方法 - 隐藏或覆盖 [英] java non-static to static method -- hiding or overriding

查看:249
本文介绍了java非静态到静态方法 - 隐藏或覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是在子类中重新定义一个非静态方法,它具有相同的一切,但是作为静态覆盖或隐藏它?

is re-defining a non-static method in a subclass with the same everything but as static overriding or hiding it ?

http: //docs.oracle.com/javase/tutorial/java/IandI/subclasses.html 说隐藏。但是当我将超类方法声明为final时,我得到一个覆盖错误。

http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html says hiding. but when i declare the superclass method as final, i get an override error.

超类声明是

final static void display() { ... }

子类:

void display() { ... }

给出覆盖错误。

推荐答案


在子类中重新定义一个非静态方法,除了as之外静态覆盖或隐藏它?

Is re-defining a non-static method in a subclass with the same everything but as static overriding or hiding it?

它不是,因为这样做会触发编译错误,导致程序无效。

It's neither, because doing so triggers a compilation error, rendering your program invalid.

class A {
    void x();
}
class B extends A {
    // ERROR!!!
    static void x();
}

当对中的两个方法都是静态方法时,会发生隐藏;当对中的两个方法都是实例方法时,会发生重写。当其中一个是静态方法而另一个是实例方法时,Java认为它是一个错误。实例方法是否为final是无关紧要的;如果静态方法在基类或派生类中也无关紧要:Java无论如何都将其称为错误。

Hiding happens when both methods in the pair are static methods; overriding happens when both methods in the pair are instance methods. When one of the two is a static method and the other one is an instance method, Java considers it an error. It does not matter if the instance method is final or not; it also does not matter if the static method is in the base or in the derived class: Java calls it an error either way.

编译器消息无法覆盖 虽然有误导性:我认为名称冲突对于这些条件来说是一个更好的名称,因为覆盖是为具有两个实例方法的情况保留的。

The compiler message that says "cannot override" is misleading, though: I think that "name collision" would have been a better name for such conditions, because "overriding" is reserved for situations with two instance methods.

这篇关于java非静态到静态方法 - 隐藏或覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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