为什么Java不允许通过实例方法隐藏静态方法? [英] Why doesn't Java allow hiding static methods by instance methods?

查看:116
本文介绍了为什么Java不允许通过实例方法隐藏静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://docs.oracle.com/javase所示/tutorial/java/IandI/override.html ,Java允许


  1. 通过实例方法覆盖实例方法并

  2. 通过静态方法隐藏静态方法

我的问题是Java不允许的原因通过实例方法隐藏静态超类方法。这可以这样做:

My question is why Java doesn't allow hiding a static superclass method by an instance method. This could be done like this:

class Base {
    static void foo () {}
}

class Derived extends Base {
    void foo () {}
    void access () {
        foo ();
        Base.foo ();
    }
}

我没有看到上述任何特殊问题方法 - 它只是作为允许隐藏静态的混乱/复杂。

I don't see any particular issue with the above approach - it is only as "messy/complex" as the (allowed) hiding of statics already is.

推荐答案

我怀疑它是为了避免与处理基类混淆。事实上,我想设计师没有看到这应该表现的明显方式。

I suspect it is to avoid confusion with dealing with the base class. In fact I imagine the designers didn't see an obvious way this should behave.

class Base {
    static void foo () {}
}

class Derived extends Base {
    void foo () {} // say this compiled
}

Base b = new Derived()
b.foo(); // should the static or the virtual method be called?

b.foo()应该调用Base.foo()还是应该调用Derived.foo( )?

Should b.foo() call Base.foo() or should it potentially call Derived.foo()?

这篇关于为什么Java不允许通过实例方法隐藏静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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