再學Java 之 解決No enclosing instance of type * is accessible

深夜,臨睡前寫了個小程序,出了點小問題java

public class Test_drive {
    
    public static void main(String[] args){
        A a = new A();              //報錯
        B b = new B();              //報錯
        System.out.println(b instanceof A);
    }
    class A{
        int a;
    }
    class B extends A{
    }
}

上面兩個語句報錯信息以下:小程序

No enclosing instance of type Test_drive is accessible. Must qualify the allocation with an enclosing instance of type Test_drive (e.g. x.new A() where x is an instance of Test_drive).

 

(1)在stackoverflow上面查找到了相似的問題:http://stackoverflow.com/questions/9560600/java-no-enclosing-instance-of-type-foo-is-accessible/9560633#9560633spa

 

(2)下面簡單說一下個人理解:code

  在這裏,A和B都是Test_drive的內部類,相似於普通的實例變量,若是類的靜態方法不能夠直接調用類的實例變量。在這裏,內部類不是靜態的內部類,因此,直接賦值(即實例化內部類),因此程序報錯。blog

 

(3)解決的方法能夠有如下兩種:get

  (1)將內部類定義爲static,即爲靜態類it

  (2)將A a = new A();B b = new B();改成:io

Test_drive td = new Test_drive();
A a = td.new A();
B b = td.new B();

 

附註:寫到這裏好睏。若是你們有更好的理解,請在下面留言。謝謝。class

相關文章
相關標籤/搜索