3

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?

5 Answers 5

8

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

Its just considered bad form / practice. Avoid this.

2 Comments

Perhaps you could give some detail on why this practice developed?
Juliet's answer pretty much sums up why it's bad - it is confusing.
1

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.

Comments

0

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

4 Comments

that's a good point. strangely enough, when I just tested your hypothesis, it does work on a null reference.
The instance can be null and the static will execute correctly.
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.