javaconstructor-chaining

Java method call in constructor chaining


Is it possible to call a constructor with the result of a method from another constructor of the same class?

I want to be able to accept input in several forms, and have something like:

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

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

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

When I try to compile this, I get

error: cannot reference this before supertype constructor has been called

refering to convertToInt.


Solution

  • You just need to make convertToInt static. Since it doesn't really rely on on anything in the class instance, it probably doesn't really belong on this class anyway.

    Here's an example:

    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;
        }
    }
    

    You have to do it this way because, behind the scenes, the super-constructor (in this case Object) needs to be called before your own constructor is run. By referring to this (via the method call) before that invisible call to super(); happens you're violating a language constraint.

    See the JLS section 8.8.7 and more of the JLS section 12.5.