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:
Why does Java permit the above code to be executed, but C++ doesn't?
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.
Every time you create an instance of a class, the runtime system creates one copy of each the class's instance variables for the instance. You can access an object's instance variables from an object as described in Using Objects.
Class VariablesWhen a number of objects are created from the same class blueprint, they each have their own distinct copies of instance variables.
All instances of an object have their own copies of instance variables, even if the value is the same from one object to another. One object instance can change values of its instance variables without affecting all other instances.
Every object can access a reference to itself with keyword this (sometimes called the this reference). When an instance method is called for a particular object, the method's body implicitly uses keyword this to refer to the object's instance variables and other methods.
Re question 2 - if you run this code, you get a StackOverflowException => Yes it creates an inifinite number of objects (well it tries...)
public class Test2 {
private Test2 subject = new Test2(); //Create Test2 object in Test2
public static void main(String[] args) throws Exception {
Test2 t = new Test2();
}
}
Why does Java permit the above code to be executed but C++ doesn't?
Since 2011, C++ also allows class members to be initalised in their declarations.
However, it wouldn't allow this case: you can only instantiate complete types, and a class type is incomplete within the class definition, so it would have to be initialised in the constructor, or by a call to a function:
class Test;
Test * make_test();
class Test {
// Test is incomplete, so "new Test" is not possible here
Test * test = make_test();
};
// Test is complete, so we can instantiate it here
Test * make_test() {return new Test;}
Java doesn't have a concept of incomplete types, so the class can be instantiated anywhere you're allowed to instantiate any class.
Does the code above create infinite objects?
Yes, trying to instantiate such a class would throw your program into a recursive death spiral.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With