![](/img/trans.png)
[英]Why am I getting a StackOverflowError when getting information from an object?
[英]Why is it showing stackoverflowerror when i am trying to create an object in it's own class?
package inheritance;
public class SingleInheritance {
// SingleInheritance obj=new SingleInheritance(); Why does this line is not giving any error when I am creating a class's object in it's own class
public static void main(String[] args) {
Plumber rahul=new Plumber();
}
}
package inheritance;
class Plumber{
Plumber ganesh=new Plumber();
// while this one is giving the stackoverflowerror.
}
當我在它自己的 class 中創建 SingleInheritance class 的 object 時,它不會拋出任何錯誤,但當我在另一個 class 中執行相同操作時拋出錯誤。 我知道在它自己的 class 中創建 object 是愚蠢的,但這發生在我嘗試做其他事情時。 我需要對正在發生的事情進行解釋。
您的代碼的問題是遞歸創建 class Plumber
對象並且沒有條件終止它。
讓我們看看您的 class Plumber
的內容及其實例化。
class Plumber
{
Plumber obj = new Plumber();
}
你認為這對創建一個new Plumber()
object 有什么作用。它將實例化一個new Plumber()
到obj
,這將反過來創建另一個new Plumber()
到obj.obj
,等等。
您當然可以在同一個 class 中保留一個 object 和一個 Plumber,但是當您想要實際初始化它時,您需要有一個特定的流程。
class Plumber
{
Plumber obj;
public Plumber()
{
if(/*condition*/)
{
obj = new Plumber();
}
}
// You can also use some methods to do so
public InstantiateObj()
{
obj = new Plumber();
}
}
這是因為您沒有實例化SingleInheritance
class。代碼
public class SingleInheritance {
SingleInheritance obj=new SingleInheritance();
public static void main(String[] args) {
Plumber rahul=new Plumber();
}
}
沒有創建SingleInheritance
的新實例,因為main
是 static function。
如果您將代碼更改為:
public class SingleInheritance {
SingleInheritance obj=new SingleInheritance();
public static void main(String[] args) {
SingleInheritance rahul=new SingleInheritance();
}
}
您將獲得相同的 Stackoverflow 異常,因為現在main
將實例化SingleInheritance
。 你得到 Stackoverflow 的原因是new Plumber()
像其他答案解釋的那樣調用它自己的構造函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.