1

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

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

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.

4

3 回答 3

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();您违反了语言约束。

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

于 2012-02-29T19:31:13.830 回答
2

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

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

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

于 2012-02-29T19:31:43.403 回答
0

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

你可以这样打电话

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

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

于 2012-02-29T19:38:04.960 回答