What could go wrong like calling a static method with an object in Java?

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 encountered when calling foo () with an instance? Does the JVM approach the first call to foo () just like a static method, or is there some technical subtlety?

+3
source share
5 answers

Its very easy to introduce subtle logic errors by invoking static methods from instances. The fact is that this does not do what you think:

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

sleep - A static method that pauses the current executable thread, not a thread instance.

+8
source

. , , A, foo().

+2

/. .

+1
source

One good reason is that you can confuse other people who may need to read or update the code. This is really “similar” because the instance of the object must be involved in the method call when in fact it is not (and in fact it can be null). This is unnecessary obfuscation.

+1
source

Not 100% sure, but you may encounter a null pointer error if your instance is null.

0
source

Source: https://habr.com/ru/post/1715726/


All Articles