JAVA允许在类内部实例化类吗?

huangapple go评论78阅读模式
英文:

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 need new

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.

huangapple
  • 本文由 发表于 2020年8月14日 13:55:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63407306.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定