is it possible to access instance methods and vari

2019-04-01 00:17发布

问题:

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