简体   繁体   中英

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. But it is frowned upon in many coding standard. Therefore some compilers and some IDEs support emitting warnings for it.

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?

It depends on the compiler settings. With eclipse default settings it will generate a warning, for example.

So try it with your compiler settings.

Generally, it does not generate an error (as defined by the 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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