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?
-
1I never understand these questions. How hard is it to try it for yourself? That way you get a correct answer immediately. This way you may not get an answer at all, and you will probably get a few incorrect answers as well.user207421– user2074212011年03月22日 01:06:31 +00:00Commented Mar 22, 2011 at 1:06
4 Answers 4
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.
Comments
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?
1 Comment
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)
9 Comments
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.