传递“这个”到这个()o super() [英] passing "this" to a this() o super()

查看:151
本文介绍了传递“这个”到这个()o super()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是:

为什么不能将this传递给构造函数的显式调用?
例如:

why can not pass "this" to an explicit call to a constructor? example:

class MyClass {

    MyClass x;

    public MyClass(MyClass c){
        x=c;
    }

    public MyClass(){
        this(this);        //error
    }

}


推荐答案

您正尝试将的引用从构造函数传递到同一实例上的另一个构造函数。

You are trying to pass a reference to this from a constructor to another constructor on the same instance.

在Java中,在从隐式或显式调用返回 this() c $ c>或 super()。这是因为超类尚未初始化。

In Java you cannot access this implicitly or explicitly in the constructor before returning from an implicit or explicit call to this() or super(). This is because the super class has not yet initialised.

您可能需要在构造函数中复制代码:

You may need to duplicate code in the constructor:

class MyClass {
    private final MyClass myInstance;
    public MyClass(MyClass myInstance) {
        this.myInstance = myInstance;
    }
    public MyClass() {
        this.myInstance = this;
    }
}

可能有办法使用私有方法破解它构造函数,但是你进入了黑客领域。

There may be ways to hack around it using a private constructor, but then you are into hacking territory.

这篇关于传递“这个”到这个()o super()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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