Java类实例递归调用 [英] Java class instance recursive calling
问题描述
我有一个非常基本的java理论问题。为什么Employee类在以下示例中以递归方式调用它?
I have a very basic java theory question. Why the Employee class calls its self recursively in the following example?
class Employee {
Employee emp = new Employee();
}
public class Manager extends Employee {
public static void main(String[] args){
Manager mgr = new Manager();
}
}
推荐答案
查看代码正在执行的操作:
Look at what the code is doing:
当您创建新的 Manager
对象时, Employee
该 Manager
对象的一部分也将被初始化(因为 Manager
extends Employee
)。
When you create a new Manager
object, the Employee
part of that Manager
object is also going to be initialized (because Manager
extends Employee
).
当 Employee
part已初始化,其 \\ temp
成员变量将被初始化。它将使用新的 Employee
对象进行初始化。但该对象还有一个 emp
成员变量,该变量将使用新的 Employee
对象进行初始化。该对象还有一个 emp
成员变量,该变量将使用新的 Employee
对象进行初始化。该对象还有一个 emp
成员变量,该变量将使用新的 Employee
对象进行初始化。该对象还有一个 emp
成员变量,该变量将使用新的 Employee
对象进行初始化。该对象还有一个 emp
成员变量,该变量将使用新的 Employee
对象进行初始化。该对象还有一个 emp
成员变量,该变量将使用新的 Employee
对象进行初始化。 ...等等,直到堆栈溢出。
When the Employee
part is initialized, its emp
member variable is going to be initialized. It will be initialized with a new Employee
object. But that object also has an emp
member variable, which will be initialized with a new Employee
object. And that object also has an emp
member variable, which will be initialized with a new Employee
object. And that object also has an emp
member variable, which will be initialized with a new Employee
object. And that object also has an emp
member variable, which will be initialized with a new Employee
object. And that object also has an emp
member variable, which will be initialized with a new Employee
object. And that object also has an emp
member variable, which will be initialized with a new Employee
object. ... etc. until the stack overflows.
这篇关于Java类实例递归调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!