Adam Matan
Adam Matan

Reputation: 136459

Java: Overloading constructors which call each other

Consider a class which is instanciated from a data found in a CSV line, and stores some of its fields. It makes sense to create two constructors for this class -one from the raw CSV line, and one with explicit variable assignment.

e.g.,

public MyClass(String csvLine)
{
    String[] fields = StringUtils.split(csvLine, ',');
    this(fields[3], fields[15], Integer.parseInt([fields[8]));
}

public MyClass(String name, String address, Integer age)
{
    this.name=name;
    this.address=address;
    this.age=age;
}

In Java, this fails because:

Constructor call must be the first statement in a constructor WhereOnEarth.java

What's the proper way to implement this?

Upvotes: 4

Views: 888

Answers (3)

Tim Büthe
Tim Büthe

Reputation: 63814

I would not mix the class that represents the parsed content and the content parsing class. I would create a MayClassFactory or something along those lines:

public class MyClassFactory {

    public MyClass fromCsvLine(String csvLine) {
        String[] fields = StringUtils.split(csvLine, ',');
        return new MyClass(fields[3], fields[15], Integer.parseInt([fields[8]));
    }

    //...
}

Upvotes: 5

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340973

Here is my take:

public class MyClass {

    public static MyClass fromCsvLine(String csvLine) {
        String[] fields = StringUtils.split(csvLine, ',');
        return new MyClass(fields[3], fields[15], Integer.parseInt([fields[8]));
    }

    //...

}

Usage:

MyClass my = MyClass.fromCsvLine("...");

Upvotes: 7

SJuan76
SJuan76

Reputation: 24895

Create a method

private init(String name, String address, Integer age) {}

Call it from both constructors.

Upvotes: 5

Related Questions