簡體   English   中英

是否可以通過類方法訪問實例方法和變量

[英]is it possible to access instance methods and variable via class methods

直到我在Oracle Doc上讀到這個(類方法不能直接訪問實例變量或實例方法 - 它們必須使用對象引用)我唯一知道的,關於實例方法和變量不能被類(靜態)方法訪問直。

當它說......他們必須使用對象參考時意味着什么? 這是否意味着我們可以使用類方法間接訪問實例變量和方法?

先感謝您。

這意味着允許這樣做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM