2017-07-02 74 views

回答

2
class A { 
    int x = 1; 

    class B { 
     int x = 2; 

     void func(int x) { 
      System.out.println(A.this.x); 
     } 
    } 
} 

使用例如:

public class Main { 
    public static void main(String[] args) {   
     A a = new A(); 
     A.B b = a.new B(); 

     b.func(0); // Out is 1 
    } 
} 
1

要訪問父實例,您可以使用這個關鍵字爲ParentClassName.this

子類必須不能是靜態

1

是的,你可以用va訪問變量x lue 1.

這裏A是你的外部類,B是非靜態內部類。

要訪問外部類A的變量x,你可以做這樣的事情

class B { 
    int x = 2; 
    void func(int x) { 
     System.out.print(A.this.x +" and "+x); 
    } 
}