英文:
How does JAVA allow class instantiation within the class?
问题
我对JAVA不熟悉。我对以下结构感到疑惑:
class MyClass {
private MyClass myClass;
//whatever
}
这不会引起无限递归吗?这是否仅仅是由于后期绑定?
英文:
Am new to JAVA. Am wondering over the following construct:
class MyClass {
private MyClass myClass;
//whatever
}
How is it that this does not cause infinite recursion? Is it only due to late-binding?
答案1
得分: 3
依赖于确切的问题是什么。有两个原因:一个是静态的(为什么它能编译),一个是动态的(为什么它能运行):
-
首先,在Java中,你永远不需要提前知道对象的大小,因为所有对象都分配在堆上,你不能在一个对象中包含另一个对象(你只能存储对事物的引用,而不是事物本身)。
-
其次,你的代码中的字段是用一个空引用创建的。在Java中,要创建一个新的实例,你总是需要使用
new
。
因此,你的示例能够编译并运行。如果你将这行代码更改为:
private MyClass myClass = new MyClass();
当尝试初始化MyClass
时,会导致堆栈溢出。
英文:
Depends on what exactly is the question. There are two reasons: one static (why it compiles) and one dynamic (why it runs):
-
Firstly, in Java you never need to know the size of objects in
advance, because all objects are allocated on heap and you cannot
have one object within another (you can only store references to
things, not the things themselves). -
Secondly, the field in your code is created with a null reference. To
create a new instance in Java you always neednew
So, your example compiles and works. If you changed the line to:
private MyClass myClass = new MyClass();
you would get a stack overflow when trying to initialize MyClass
.
答案2
得分: 1
myClass
的值不会默认实例化。默认情况下,它将为null
。
英文:
The value of myClass
will not be instantiated by default. By default it will be null
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论