简体   繁体   English

使用Java中的对象调用静态方法会出现什么问题?

[英]What could go wrong with 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 that may arise from calling foo() using an instance? 使用实例调用foo()可能会出现任何问题吗? Does the JVM treat the first call to foo() exactly as a static method, or is there some technical subtlety? JVM是否将第一次调用foo()完全视为静态方法,还是存在一些技术细微之处?

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. sleep是一个静态方法,它暂停当前正在执行的线程,而不是线程实例。

The two calls are the same. 这两个电话是一样的。 The problem that comes to mind is when overriding class A, you cannot directly override foo(). 想到的问题是当重写A类时,不能直接覆盖foo()。

Its just considered bad form / practice. 它只是被认为是糟糕的形式/做法。 Avoid this. 避免这样做。

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). 它真的“看起来”像实例化对象应该参与方法调用,而实际上它不是(实际上它可以为null)。 It's unnecessary obfuscation. 这是不必要的混淆。

不是100%肯定,但如果您的实例为null,则可能会遇到空指针异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM