从实例引用Java中的静态方法/变量 [英] Reference Static Methods/Variables in Java from an Instance

查看:121
本文介绍了从实例引用Java中的静态方法/变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释为什么java允许您从实例访问静态方法和成员吗?一个不好的例子,如果我有一个名为RedShape的对象并且它有一个名为getColor()的静态方法返回red,为什么java允许你从RedShape实例调用静态方法?对我来说,这似乎违反了OO语言设计的一些核心概念。至少,它应该带有编译器警告。

Can anyone explain to me why java allows you to access static methods and members from an instance? A bad example, if I have an object called RedShape and it has a static method called getColor() which returns "red", why does java allow you to call the static method from an instance of RedShape? To me this seems to violate some of the core concepts of OO language design. At the least, it should come with a compiler warning.

提前致谢。

编辑:

特别是,我问你何时有类似的东西

In particular, I'm asking about when you have something like

RedShape test = new RedShape();
test.getColor();

其中getColor是RedShape类的静态方法。这没有任何意义,它是允许的,并没有通过javac在命令行上给出编译器警告。我看到它强烈气馁,但是如果有一个技术或合理的理由背后为什么它被允许在因为C ++允许它之外,这很奇怪。

where getColor is a static method of the RedShape class. This doesn't make any sense that it's allowed and doesn't give a compiler warning on the command line via javac. I see that it's "strongly discouraged", but was curious if there was a technical or reasonable reason behind why it's allowed outside of "because C++ allows it."

推荐答案

你真的没有理由这么做。

There's really no reason why you can actually do this.

我唯一的猜测就是它会允许你覆盖静态方法,但是你不能

My only guess was that it would allow you to override static methods, but you can't.

如果您尝试以下方案:

香蕉有一个名为'test'的静态方法(打印'banana')
Apple扩展Banana并覆盖名为'test'的静态方法(打印'apple')

Banana has a static method called 'test' (this prints 'banana') Apple extends Banana and "overrides" the static method called 'test' (this prints 'apple')

你做这样的事情:

public static void main(String[] args) {
    Apple apple = new Apple();
    Banana banana = new Banana();
    Banana base = new Apple();

    apple.test();
    banana.test();
    base.test();
}

结果输出为:

apple
banana
banana

如此有效,它毫无用处。

So effectively, it's pretty useless.

这篇关于从实例引用Java中的静态方法/变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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