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 开发者_如何学Cclass 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.
精彩评论