简体   繁体   English

使用引用变量调用静态方法

[英]static method calling using reference variable

 Duck d = new Duck();
 string[] s = {};
 d.main();

Will the compiler generate an error as we are trying to call a static method using a reference variable instead of the class name?当我们尝试使用引用变量而不是类名调用静态方法时,编译器会产生错误吗?

It is legal Java as defined by the JLS to call a static method via a reference. JLS定义的通过引用调用静态方法是合法的 Java。 But it is frowned upon in many coding standard.但它在许多编码标准中都不受欢迎。 Therefore some compilers and some IDEs support emitting warnings for it.因此,一些编译器和一些 IDE 支持为它发出警告。

If you use a standard compiler, it won't.如果您使用标准编译器,则不会。

But it should.但它应该。

You should never ever call a static method that way.你永远不应该那样调用静态方法。 There's absolutely no value whatsoever in doing so, it isn't quicker or more readable, but it's a ticking time bomb.这样做绝对没有任何价值,它不会更快或更具可读性,但它是一颗定时炸弹。 Consider this scenario:考虑这种情况:

class A {
    static void bar() {
        System.out.println( "A" );
    }
}

class B extends A {
    static void bar() {
        System.out.println( "B" );
    }
}

Then somewhere in your code, you do this:然后在你的代码中的某个地方,你这样做:

    A foo = new B();
    foo.bar();

Now, which bar() method is being called here?现在,这里调用了哪个bar()方法?

It depends on the compiler settings.这取决于编译器设置。 With eclipse default settings it will generate a warning, for example.例如,使用 eclipse 默认设置它会生成一个警告。

So try it with your compiler settings.因此,请尝试使用您的编译器设置。

Generally, it does not generate an error (as defined by the JLS)通常,它不会产生错误(由 JLS 定义)

First to your question,the answer is no.Obviously,you can use a reference variable instead of the class name to call a static method inside the class,but just because it's legal doesn't mean that it's good.Although it works,it makes for misleading and less-readable code.When you say d.main(),the compiler just automatically resolves it back to the real class.首先对于你的问题,答案是否定的。显然,你可以使用引用变量而不是类名来调用类内部的静态方法,但仅仅因为它是合法的并不意味着它是好的。虽然它有效,但它造成误导和可读性差的代码。当你说 d.main() 时,编译器会自动将它解析回真正的类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM