2017-10-08 55 views
0

我知道這是錯誤的,但我想知道爲什麼我收到獲取stackOverflowError異常的原因是什麼?

class Student{ 

    String student; 
    int rollno; 

    Student stud=new Student("s",20);//(1st object)Thrown exception because of this line 

    Student(String student,int rollno){ 
     this.student=student; 
     this.rollno=rollno; 
     } 


    public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    Student stud=new Student("R",101); 


    } 

    } 
Exception in thread "main" java.lang.StackOverflowError 
at sai.Student.<init>(Student.java:8) 
at sai.Student.<init>(Student.java:8)......... 

的原因。當我創建了一個對象(即第一個對象),我不會得到這個錯誤,但是當我創建了兩個對象,我得到這個錯誤。

+0

您沒有創建兩個對象。您正在嘗試創建無限數量的對象。 – Eran

+0

你能解釋一下如何創建無限對象嗎? – Swati

回答

0

A StackOverflowError發生在應用程序遞歸過深並且調用堆棧達到其極限時。在你的情況下,創建一個Student的實例初始化它的所有成員,包括stud,它本身是一個Student - 所以它初始化它的所有成員,包括它的stud等,直到命中錯誤。

0

當一個新的Student對象被創建時,它的所有字段都被初始化。 這意味着

字符串的學生; int rollno; Student stud = new Student(「s」,20);

全部發生。前兩個語句是無害的,但是當第三條語句被執行時,它會嘗試創建一個新的Student對象,這會導致另一個初始化> String student;

int rollno; 
Student stud=new Student("s",20); 

而這又導致了另一個初始化等進行,直到你得到上面的行StackOverflow的錯誤

0
Student stud=new Student("R",101); 

1.首先被執行,然後下面的行執行

class Student{ 

String student; 
int rollno; 

Student stud=new Student("s",20); 

2.因爲學生stud = new Student(「s」,20)再次在行下面wil我得到執行和這個過程繼續,由於我們得到stackoverflowError異常。

類學生{

String student; 
int rollno; 

Student stud=new Student("s",20); 

當我創建了一個對象(即第一個對象),我不會得到這個錯誤,但是當我創建了兩個對象,我得到這個錯誤。

** ANnswer:**由於我們沒有在主寫任何東西所以控制不會去到第二步

0

正如@Mureinik已經提到,

Student stud=new Student("s",20); 

以上線是無限的原因循環,因爲當你在初始化成員變量Student期間創建Student的實例時,它會進入無限循環。作爲它自己的創造對象。

==編輯==

沒有聲明Student型變量作爲成員變量,這是我可以看到的點。所以,你應該從它的成員變量中刪除它。最終的代碼應該看起來像

class Student{ 

String student; 
int rollno; 

Student(String student,int rollno){ 
    this.student=student; 
    this.rollno=rollno; 
    } 

public static void main(String[] args) { 
Student stud1 = new Student("R",101); 
//use stud instance 

Student stud12 = new Student("V",11); // create another instance 

    } 
} 
+0

私人學生學生; ---由於這一行我們將得到NullPointerException – Swati

+0

@Swati不,你不會的。由於程序從主要方法和OP已經初始化stud之前使用它 – Ravi

+0

請檢查,我試着在IDE上執行它我得到一個空指針異常 – Swati

相關問題