2017-07-02 68 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); 
    } 
}