【问题标题】:is it possible to access instance methods and variable via class methods是否可以通过类方法访问实例方法和变量
【发布时间】:2023-03-21 21:37:01
【问题描述】:

直到我在 Oracle Doc 上读到这个(类方法不能直接访问实例变量或实例方法——它们必须使用对象引用)我才知道,关于实例方法和变量不能被类访问( static) 方法。

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

提前谢谢你。

【问题讨论】:

标签: java class methods


【解决方案1】:

表示允许这样做:

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
    }
}

【讨论】:

    【解决方案2】:

    实例变量,顾名思义,与类的实例相关联。因此,直接从与任何特定实例无关的类方法访问它是没有意义的。因此,要访问实例变量,您必须有一个可以从中访问实例变量的类的实例。

    反之则不然——类变量位于“顶层”,因此实例方法和变量可以访问。

    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.
     }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-03
      • 2017-03-20
      • 1970-01-01
      • 1970-01-01
      • 2020-10-10
      • 2021-11-24
      • 2017-06-18
      • 2019-09-20
      相关资源
      最近更新 更多