是否可以通过 class 方法访问实例方法和变量

is it possible to access instance methods and variable via class methods

直到我在 Oracle Doc 上读到这个(Class 方法不能直接访问实例变量或实例方法——它们必须使用对象引用)我唯一知道的是,关于实例方法和变量不能可以通过 class(static) 方法直接访问。

它说....他们必须使用对象引用是什么意思?这是否意味着我们可以使用 class 方法间接访问实例变量和方法?

提前谢谢你。

表示允许这样:

public class Test {
    public int instanceVariable = 42;
    public void instanceMethod() {System.out.println("Hello!");}

    public static void staticMethod() {
        Test test = new Test();

        System.out.println(test.instanceVariable); // prints 42
        test.instanceMethod(); // prints Hello!
    }
}

这不是:

public class Test {
    public int instanceVariable = 42;
    public void instanceMethod() {System.out.println("Hello!");}

    public static void staticMethod() {
        System.out.println(instanceVariable); // compilation error
        instanceMethod(); // compilation error
    }
}

实例变量,顾名思义,绑定到 class 的实例。因此,直接从未绑定到任何特定实例的 class 方法访问它是没有意义的。因此,要访问实例变量,您必须有一个 class 的实例,您可以从中访问实例变量。

反之则不然 - class 变量位于 "top level",因此实例方法和变量可以访问。

class MyClass;
{  
 public int x = 2;
 public static int y = 2;

 private int z = y - 1; //This will compile.

 public static void main(String args[])
 {
    System.out.println("Hello, World!");
 }

 public static void show()
 {
    System.out.println(x + y); // x is for an instance, y is not! This will not compile.

    MyClass m = new MyClass();
    System.out.println(m.x + y); // x is for the instance m, so this will compile.
 }

 public void show2()
 {
  System.out.println(x + y); // x is per instance, y is for the class but accessible to every instance, so this will compile.
 }
}