rubixibuc
rubixibuc

Reputation: 7397

Calling static methods on object instances and a side note Java

I was looking of some of the questions, and it lead me to this issue. When you call a static method on a object instances, does it resolve dynamically or statically for example:

class A
{
     public static foo() {}
}
class B extends A
{
     public static foo() {}
}
[...]
public static void main(String[] args)
{
     A a = new B();
     a.foo(); // does this all A foo or B foo?
}

why I'm asking this is because it would explain why static methods can't be abstract. Because if A was an interface this would not work if foo was abstract and static.

How does this work internally? Basically how does is know that foo is static to begin with if it doesn't do anything dynamic? Doesn't it still have to inspect the class? Also if it know a is really a B why doesn't it call foo on B?

Upvotes: 1

Views: 71

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500215

It resolves it statically based on the compile-time type of a. The value is ignored, and can even be null:

A a = null;
a.foo(); // Still calls A.foo

IIRC, at one point it did perform a nullity check, but it doesn't now.

I would strongly urge you not to do this, and at least some IDEs (including Eclipse) can warn you about this. The code doesn't do what it looks like, and sometimes it can be very misleading:

Thread t = new Thread(new Runnable() { /* ... */ });
t.start();
t.sleep(1000);

That looks like it makes the newly created thread sleep - but actually it's the current thread which will sleep. Eek!

IMO, this was effectively a mistake in the design of Java.

Upvotes: 6

Related Questions