Java类实例递归调用 [英] Java class instance recursive calling

查看:95
本文介绍了Java类实例递归调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常基本的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆