2017-03-24 5 views
1

これは私のコードです。そのStackOverflowのエラーが生じ:スレッド "main"の例外:java.lang.StackOverflowError、なぜですか?

public class NucleousInterviewQuestion { 

NucleousInterviewQuestion interviewQuestion = new NucleousInterviewQuestion(); 

public NucleousInterviewQuestion() { 
    // TODO Auto-generated constructor stub 
} 

public static void main(String[] args) { 
    NucleousInterviewQuestion interviewQuestion= new NucleousInterviewQuestion(); 
} 
} 

答えて

6

ここでこの:

public class NucleousInterviewQuestion { 
    NucleousInterviewQuestion interviewQuestion = new NucleousInterviewQuestion(); 

は無限再帰を作成します。

ポイントは:あなたのメインメソッドでnewと呼んでいます。これを行うと、このクラスに属する "init"コードが実行されます。 「初期化」のコードの構成は次のとおりです。

  • フィールドのinit文
  • とコンストラクタ呼び出し

そして、あなたは、initコードを持っている一つのフィールド...再びnewを呼び出しました。非常に同じクラスのために。

その意味での「解決策」:クラスの初期化方法を理解する。もちろん、クラスは他のオブジェクトを参照するフィールドを持つことができます。同じクラスのオブジェクトさえも。しかし、あなたは次のようなものが必要です:

public class Example { 
    Example other; 

    public Example() { 
    other = null; 
    } 

    public Example(Example other) { 
    this.other = other; 
    } 

このようにして、同じクラスの別のオブジェクトを参照することができます。再帰を作成せずに。

2

フィールドinterviewQuestionは別のNucleousInterviewQuestionオブジェクトを作成していますが、この新しいオブジェクトは別のものを作成しています - 再帰...

関連する問題