2016-11-14 98 views
1

我收到錯誤如下:學生出錯a =新生();

Exception in thread "main" java.lang.Error: Unresolved compilation problem:

No enclosing instance of type New is accessible. Must qualify the allocation with an enclosing instance of type New (e.g. x.new A() where x is an instance of New). at n.New.main(New.java:7)

以下是我的代碼:

package n; 

public class New 
{ 

    public static void main(String[] args) 
    { 
     Student a=new Student(); 
     a.name="abc"; 
     a.number=6; 
     a.marks=1; 

     System.out.println(a.name); 
     System.out.println(a.number); 
     System.out.println(a.marks); 
    } 

    class Student 
    { 
     String name; 
     int number; 
     int marks; 

    } 

} 
+0

@SantoshReddy你真的*讀過*的錯誤信息? – Biffen

+2

@ magic-sudo這兩個評論都是錯誤的,不需要做實際的事情,也不是編譯錯誤的錯誤 – SomeJavaGuy

+0

這是什麼關於。其實我是一個初學者。你能告訴我這些改變嗎? –

回答

2

你的類學生是不是靜態的,你正試圖從這是不允許的靜態上下文訪問它。

您的代碼應如下所示:

package n; 

public class New { 

    public static void main(String[] args) { 
     Student a = new Student(); 
     a.name = "abc"; 
     a.number = 6; 
     a.marks = 1; 

     System.out.println(a.name); 
     System.out.println(a.number); 
     System.out.println(a.marks); 
    } 

    static class Student { 
     String name; 
     int number; 
     int marks; 

    } 

} 
+0

感謝@chirag parmar。我知道了。 –

+0

@SantoshReddy一般來說,製作靜態類是不好的做法。你可以通過引用外部類來訪問內部類。你真的需要一個內部類嗎? – iMBMT

+0

雅...我同意@iMBMT .. –

1

Student是一個非靜態內部類的類New的,並且必須從類New的目的被訪問。它不能直接從main訪問,因爲main是靜態的,並且Student不是。作爲一個解決方案,只是其聲明外New這樣的:發生

package n; 

public class New { 

    public static void main(String[] args) { 
     Student a = new Student(); 
     a.name = "abc"; 
     a.number = 6; 
     a.marks = 1; 

     System.out.println(a.name); 
     System.out.println(a.number); 
     System.out.println(a.marks); 
    } 
} 

class Student { 
    String name; 
    int number; 
    int marks; 

} 
1

的編譯錯誤,因爲Student是一個內部類的New

由於Student被定義爲class Student,它只能存在於New的實例中。所以有幾種方法可以解決這個「問題」。

最簡單的一個:讓

static class Student 

由於這一點,勢必Student isn't的單個實例中的New一個實例存在。

另外一個是創建在您創建的Student實例的New一個實例:

Student a = new New().new Student(); 

但開始學習如何編程的目的,我會說:取下內Student類從Student開始是外部類。

public class Student { 
    String name; 
    int number; 
    int marks; 

    public static void main(String[] args) { 
     Student a = new Student(); 
     a.name = "abc"; 
     a.number = 6; 
     a.marks = 1; 

     System.out.println(a.name); 
     System.out.println(a.number); 
     System.out.println(a.marks); 
    } 
} 

一些補充了入門:

包括Student構造爲Student(String, int, int),並調用它初始化時Student一個新實例,而不是對其進行初始化和之後設置變量:

new Student("abc", 1, 6); 
0

當您試圖從出現錯誤的靜態上下文訪問它時,您的內部類應該是靜態的。

static class Student { 
     String name; 
     int number; 
     int marks; 

    }