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?
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("...");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With