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

时间:2012-02-29 19:28:54

标签: java 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

3 个答案:

答案 0 :(得分:4)

您只需要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)。在对this的隐形调用发生之前,通过引用super();(通过方法调用),您违反了语言约束。

请参阅the JLS第8.8.7节和more of the JLS第12.5节。

答案 1 :(得分:2)

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

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

表示构造函数完成之前convertToInt

答案 2 :(得分:0)

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

你可以像这样打电话

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

使方法静态可能会解决您的问题。

相关问题