Riaz Ud Din
Riaz Ud Din

Reputation: 169

Java class instance recursive calling

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();

    }
}

Upvotes: 2

Views: 1598

Answers (3)

Jesper
Jesper

Reputation: 206796

Look at what the code is doing:

When you create a new Manager object, the Employee part of that Manager object is also going to be initialized (because Manager extends 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.

Upvotes: 4

BambooleanLogic
BambooleanLogic

Reputation: 8161

class Employee {
    Employee emp = new Employee();
}

What this means is that each Employee contains an instance of another Employee. As such, when your Employee is constructed, it also has to create the Employee it contains. However, by the same logic, that Employee must also have its own child Employee that must be constructed, and so on.

Upvotes: 0

giannis christofakis
giannis christofakis

Reputation: 8321

Skip the commented object creation, every time you create an Employee which happens when you create Manager because it inherits it, it enters an internal loop.

class Employee {

//Employee emp = new Employee();

}

Upvotes: 0

Related Questions