2017-03-07 77 views
0

我在使用Java中定義的類創建對象時遇到了錯誤。 這裏是我的代碼:在java中創建對象時給我一個錯誤

public class encapsulation { 

    class Emp 
    { 
     int empId; 
     String empName; 
    } 

    public static void main(String[]args) 
    { 
     Emp e1 = new Emp(); 
    } 
} 

但它給我一個錯誤:

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

這裏是一個screeshot:Error in object creation using java

回答

2

您試圖實例化一個內部類的對象。內部類實例始終需要與外部類實例關聯。試試這個 -

public static void main(String[]args) 
{ 
    encapsulation en = new encapsulation(); 
    encapsulation.Emp e1 = en.new Emp(); 
} 

查看the official tutorial瞭解更多信息。

2

當你有一個內部類中encapsulationEmp,任何實例Emp屬於一個實例encapsulation。如果你不希望出現這種情況,使它成爲一個嵌套類代替,通過添加改性劑static

public class encapsulation { 
    static class Emp { 
    ...... 

現在Emp聲明static,它不屬於任何encapsulation特定實例,所以你不」 t需要實例化encapsulation以實例化Emp

+0

謝謝。它的工作原理 –

+0

@ErPriyatam很高興爲您服務。 – khelwood

相關問題