Alex Rivera | Logout

Object of the class as instance variable inside the class

Asked 2012-11-28T14:45:26.940
12

Possible Duplicate:
How can a class have a member of its own type, isnt this infinite recursion?

The Code:

public class Test2{
    private Test2 subject = new Test2(); //Create Test2 object in Test2
    private int num;
}

The Questions:

  1. Why does Java permit the above code to be executed, but C++ doesn't?

  2. Does the code above create infinite number of objects? Since Test2 itself contains a Test2 object which again contains a Test2 object which itself has a Test2 object and so on.

Edit
Report

1 Answer

0

since you can have multiple constructors its allowed. if you only have one constructor this would indeed result in an infinite loop.

public class Test{
    private Test a;

    public Test(String s){
        this.a=new Test();
    }

    public Test(){

    }

}
answered 2012-11-28T14:49:24.740

Your Answer