繁体   English   中英

构造函数链接中的Java方法调用

[英]Java method call in constructor chaining

是否可以使用同一类的另一个构造函数的方法结果调用构造函数?

我希望能够接受几种形式的输入,并具有以下内容:

public class MyClass
{
    public MyClass(int intInput)
    {
    ...
    }

    public MyClass(String stringInput);
    {
        this(convertToInt(stringInput));
    }

    public int convertToInt(String aString)
    {
        return anInt;
    }
}

当我尝试编译它时,我得到

error: cannot reference this before supertype constructor has been called

引用convertToInt

您只需要使convertToInt静态。 由于它实际上并不依赖于类实例中的任何内容,因此它可能实际上并不真正属于该类。

这是一个例子:

class MyClass {
    public MyClass(String string) {
        this(ComplicatedTypeConverter.fromString(string));
    }

    public MyClass(ComplicatedType myType) {
        this.myType = myType;
    }
}

class ComplicatedTypeConverter {
    public static ComplicatedType fromString(String string) {
        return something;
    }
}

您必须这样做,因为在幕后,需要在运行自己的构造函数之前调用超级构造函数(在本例中为Object)。 通过在对super();无形调用之前引用this (通过方法调用super(); 发生您违反语言限制的情况。

请参阅JLS第8.8.7节和JLS第12.5节的更多内容。

不能调用convertToInt方法,因为它需要由一个对象运行,而不仅仅是一个类。 因此,将代码更改为

public static int convertToInt(String aString)
{
    return anInt;
}

表示在构造函数完成之前convertToInt

没有不可能。 要调用实例方法,必须已调用所有您的超类构造函数。 在这种情况下,您要调用this()来代替对super()的调用。 您也不能在同一函数中同时拥有super()和this()。 因此,在您的情况下,未初始化超类实例,因此您将收到此错误。

你可以这样打

public MyClass(String stringInput) {
    super(); // No need to even call... added just for clarification
    int i = convertToInt(stringInput);
}

将方法设为静态可能会解决您的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM