Reputation: 11
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?
Upvotes: 1
Views: 1639
Reputation: 21
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.
Upvotes: 0
Reputation: 597116
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)
Upvotes: 1
Reputation: 49744
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?
Upvotes: 3