为什么要在类的构造函数中初始化子类,类的子类类必须是静态的? [英] Why does a sub-class class of a class have to be static in order to initialize the sub-class in the constructor of the class?

查看:93
本文介绍了为什么要在类的构造函数中初始化子类,类的子类类必须是静态的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,正如我所写的,这个问题或多或少。
我知道可能根本不清楚,所以我举个例子。

So, the question is more or less as I wrote. I understand that it's probably not clear at all so I'll give an example.

我有Tree类,其中有Node类,并且Tree的空构造函数被写为:

I have class Tree and in it there is the class Node, and the empty constructor of Tree is written:

public class RBTree {
    private RBNode head;

    public RBTree(RBNode head,RBTree leftT,RBTree rightT){
        this.head=head;
        this.head.leftT.head.father = head;
        this.head.rightT.head.father = head;
    }

    public RBTree(RBNode head){
        this(head,new RBTree(),new RBTree());
    }

    public RBTree(){
        this(new RBNode(),null,null);
    }  

    public class RBNode{
        private int value;
        private boolean isBlack;
        private RBNode father;
        private RBTree leftT;
        private RBTree rightT;
    }
}

Eclipse给了我错误:没有封闭的实例由于对空构造函数中的 new RBTree()进行了一些中间构造函数调用,因此可以使用RBTree类型。
但是,如果我将RBNode更改为静态类,就没有问题。

Eclipse gives me the error: "No enclosing instance of type RBTree is available due to some intermediate constructor invocation" for the "new RBTree()" in the empty constructor. However, if I change the RBNode to be a static class, there is no problem.

那当类为静态时,为什么它可以工作?

So why is it working when the class is static.

顺便说一句,我找到了一个针对cunstructor的简单解决方案:

BTW, I found an easy solution for the cunstructor:

public RBTree(){
    this.head = new RBNode();
}

所以,我不知道第一段代码是什么问题。

So, I have no idea what is the problem in the first piece of code.

推荐答案

基本上,内部类(没有static修饰符)对其外部类的实例具有隐式引用,因此它在创建外部类之前无法创建。通过在对 this 的调用上创建一个,它无法引用外部类,因为直到调用super之后,外部类才构建得太多。在适合您的情况下,对head的赋值发生在对super的(隐式)调用之后,因此该类的构造足以获取对其的引用。

Basically an inner class (without the static modifier) has an implicit reference to an instance of its outer class, so it can't be created until the outer class is created. By creating one on the call to this it can't reference the outer class yet because the outer class isn't constructed much at all until after the call to super. The case that works for you, the assignment to head happens after the (implicit) call to super so the class is constructed enough to get a reference to it.

所有这些规则可防止您通过引用未初始化的对象并发生Bad Things(TM)来使自己陷入困境。

All of these rules prevent you from shooting yourself in the foot by referencing an uninitialized object and having Bad Things (TM) happen.

这篇关于为什么要在类的构造函数中初始化子类,类的子类类必须是静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆