请帮助我找出为什么在运行以下代码时出现 StackOverflowError 异常。
public class HelloParent {
HelloParent checking = new HelloParent();
public class Hello{
public void printFunction() {
checking.printHW("hello ");
}
}
private void printHW(String s){
System.out.println(s);
}
public static void main(String[] args) {
HelloParent helloParent = new HelloParent();
Hello hello = helloParent.new Hello();
hello.printFunction();
}
}
这里我试图从内部类访问父类方法。
最佳答案
HelloParent
有一个实例字段,checking
,它是这样声明和初始化的:
HelloParent checking = new HelloParent();
该代码被插入到每个 HelloParent
构造函数*的开头。该代码调用 HelloParent
构造函数,因此再次运行,因此再次调用构造函数,因此再次运行,等等。
你不能有一个实例字段来调用它在其中定义的类的构造函数。
* 从技术上讲,就在调用 super()
之后(在本例中是隐式调用)。
关于java - 从内部类访问父方法时出现 StackOverflowError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44106817/