Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 357
Adam Matan Avatar asked Dec 03 '22 04:12

Adam Matan


1 Answers

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("...");
like image 58
Tomasz Nurkiewicz Avatar answered Dec 09 '22 14:12

Tomasz Nurkiewicz