为什么我不能只声明所有方法静态?

4 java

我被这个问题质疑,为什么我不能声明所有方法都是静态的?你能在这里给我一个解释吗?谢谢.

我相信当你创建一个静态方法时,它无法访问非静态成员?

Syn*_*sso 5

您可以.没有理由从这样的类中实例化对象.任何州都是JVM的全局.

你的提问者可能会混淆"不能"和"不应该".


Oh *_*oon 4

静态方法不能访问实例变量。:)

public class MyStaticExample{
  private String instanceVariable = "Hello";
  private static String STATIC_VARIABLE = "Hello too";

  public static void staticMethod(){
    System.out.println(this.instanceVariable); // this will result in a compilation error.
    System.out.println(STATIC_VARIABLE); // this is ok
  }

  public void instanceMethod(){
    System.out.println(this.instanceVariable); // this is ok
    System.out.println(STATIC_VARIABLE); // this is ok
  }
}
Run Code Online (Sandbox Code Playgroud)