deep
deep

Reputation: 11

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?

Upvotes: 1

Views: 1639

Answers (4)

Trusty Tiger
Trusty Tiger

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

Bozho
Bozho

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

biziclop
biziclop

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

jmg
jmg

Reputation: 7414

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.

Upvotes: 5

Related Questions