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

落花浮王杯 提交于 2020-01-01 06:33:12

问题


Till I read this on Oracle Doc (Class methods cannot access instance variables or instance methods directly—they must use an object reference) the only thing I know, about instance methods and variables are not able to be accessed by the class(static) methods directly.

What does it mean when it says ....they must use an object reference? Does it mean we can access instance variables and methods indirectly using class methods?

Thank you in advance.


回答1:


It means that this is allowed:

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

and this is not:

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:


An instance variable, as the name suggests is tied to an instance of a class. Therefore, accessing it directly from a class method, which is not tied to any specific instance doesn't make sense. Therefore, to access the instance variable, you must have an instance of the class from which you access the instance variable.

The reverse is not true however - a class variable is at the "top level", and so is accessible to instance methods and variables.

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


来源:https://stackoverflow.com/questions/28006799/is-it-possible-to-access-instance-methods-and-variable-via-class-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!