如何一个类有自己的类型的成员,不是这个无限递归? [英] How can a class have a member of its own type, isn't this infinite recursion?
问题描述
假设我定义了一个类,该类的成员变量与自身类型相同。
Say I define a class that has as a member a variable of the same type as itself.
public class abc {
private abc p;
}
这实际上是有效的,
为什么我认为它不应该:创建一个 abc
的实例,它包含一个< c $ c> abc ,其中包含 abc
类型的变量,其中包含 abc
,其中.....
Why I think it shouldn't: creating an instance of abc
, it contains a variable of type abc
, which contains a variable of type abc
, which contains a variable of type abc
, which .....
显然我错了,有人能告诉我如何?
Obviously I'm wrong, could someone enlighten me as to how?
推荐答案
你只声明变量而不创建它。尝试在声明或构造函数中创建它,并让我知道会发生什么:
You're only declaring the variable and not creating it. Try creating it at declaration or in the constructor and let me know what happens:
public class Abc {
private Abc p = new Abc(); // have fun!
public static void main(String[] args) {
new Abc();
}
}
顺便提一下,如果你不在类,而是在getter方法或构造函数参数中接受对它的引用,您的代码将正常工作。这是一些链接列表的工作原理。
Incidentally, if you don't create it in the class, but rather accept a reference to it in a getter method or a constructor parameter, your code will work just fine. This is how some linked lists work.
这篇关于如何一个类有自己的类型的成员,不是这个无限递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!