类的对象作为类中的实例变量 [英] Object of the class as instance variable inside the class
本文介绍了类的对象作为类中的实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Possible Duplicate:
How can a class have a member of its own type, isnt this infinite recursion?
代码:
public class Test2{
private Test2 subject = new Test2(); //Create Test2 object in Test2
private int num;
}
问题:
-
为什么Java允许执行上述代码,但C ++不执行?
Why does Java permit the above code to be executed, but C++ doesn't?
上面创建无限多个对象?由于 Test2
本身包含 Test2
对象,其中还包含 Test2
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.
推荐答案
问题2 - 如果你运行这个代码,你会得到一个StackOverflowException =>是的,它会创建无限数量的对象(试试...)
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();
}
}
这篇关于类的对象作为类中的实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文