为什么在构造函数中调用此函数会产生计算器错误?
Why calling this function in the constructor creates stackoverflow error?
您好,我有一个 Person
class,它有一个实例化 Person father
的方法 fatherComesFirst
。但是,当我在构造函数中调用此方法时,为什么 jvm
会抛出 Whosebug
错误?我是初学者。虽然我相信到目前为止我是正确的。
我的代码。
package intermediate;
public class Person {
//getters & setters
private String firstName;
private String lastName;
public Person(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
fatherComesFirst("",lastName);
}
public void fatherComesFirst(String firstName, String lastName){
Person father = new Person(firstName,lastName);
System.out.println(father.getFirstName()+" "+father.getLastName());
}
}
因为每当您创建 Person()
class 的实例时,它都会调用函数 fatherComesFirst()
,该函数会在该函数的第一行创建同一个 class。这是一个无限循环。
这本质上是一个无限循环。每当命中构造函数时,它都会调用一个实例化另一个 Person 的函数。实例化此 Person 时,它还会调用实例化另一个 Person 的同一函数,该函数在构造中也调用该函数......好吧,你明白了。
您好,我有一个 Person
class,它有一个实例化 Person father
的方法 fatherComesFirst
。但是,当我在构造函数中调用此方法时,为什么 jvm
会抛出 Whosebug
错误?我是初学者。虽然我相信到目前为止我是正确的。
我的代码。
package intermediate;
public class Person {
//getters & setters
private String firstName;
private String lastName;
public Person(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
fatherComesFirst("",lastName);
}
public void fatherComesFirst(String firstName, String lastName){
Person father = new Person(firstName,lastName);
System.out.println(father.getFirstName()+" "+father.getLastName());
}
}
因为每当您创建 Person()
class 的实例时,它都会调用函数 fatherComesFirst()
,该函数会在该函数的第一行创建同一个 class。这是一个无限循环。
这本质上是一个无限循环。每当命中构造函数时,它都会调用一个实例化另一个 Person 的函数。实例化此 Person 时,它还会调用实例化另一个 Person 的同一函数,该函数在构造中也调用该函数......好吧,你明白了。