views:

153

answers:

5

If I have the following:

class A {
  public A() { }
  public static void foo() { System.out.println("foo() called"); }
}

public class Main {
  public static void main(String [] args) {
    A a = new A();
    a.foo(); // <-- static call using an instance.
    A.foo(); // <-- static call using class
  }
}

Are there any problems that may arise from calling foo() using an instance? Does the JVM treat the first call to foo() exactly as a static method, or is there some technical subtlety?

+2  A: 

The two calls are the same. The problem that comes to mind is when overriding class A, you cannot directly override foo().

Alex B
A: 

Not 100% sure, but you may risk hitting a null pointer exception if your instance is null.

patros
that's a good point. strangely enough, when I just tested your hypothesis, it *does* work on a null reference.
Jeremy Powell
The instance can be null and the static will execute correctly.
Doomspork
Yes, that's why I said I wasn't sure. The VM must be smart enough to get the function from the class instead of the instance.
patros
Static methods belong to the class, not an instance, and they're bound at compile time - the content of the variable is utterly irrelevant, only its declared type matters.
Michael Borgwardt
+8  A: 

Its very easy to introduce subtle logic errors by calling static methods from instances. Case in point, this doesn't do what you think it does:

Thread t = new Thread(...);
t.sleep(1000);

sleep is a static method which pauses the currently executing thread, not the thread instance.

Juliet
+1  A: 

Its just considered bad form / practice. Avoid this.

Eric Anderson
Perhaps you could give some detail on why this practice developed?
Alex Feinman
Juliet's answer pretty much sums up why it's bad - it is confusing.
Peter Recore
+1  A: 

One good reason is that you can confuse other people who might need to read or update your code. It really "seems" like the instantiated object should be involved in the method call, when in fact it isn't (and in fact it can be null). It's unnecessary obfuscation.

Alex Feinman