I was told by a Professor that explicit constructor invocation using this was "poor coding practice" and penalized for it. However, I haven't been able to find anything in any java style guide that I've looked through that comments on it one way or another. On top of that, it seems to be done in quite a bit of coding examples that I have seen. I was hoping to get some input on whether this is poor coding practice and why.
An example of what I am referring to:
public class SomeClass {
private int a;
private int b;
public SomeClass() {
this(0);
}
public SomeClass(int a) {
this(a, 0);
}
public SomeClass(int a, int b) {
this.a = a;
this.b = b;
}
}
EDIT: His comment exactly was "One constructor calling a constructor of the same class is not good practice. A constructor creates an object, so calling a constructor that calls another constructor what is happening in memory? Something to thing about."
And this was the specific code:
public class Employee {
private String name;
private int monthlySalary;
// Default constructor
public Employee() {
this("", 0);
}
// Constructor
public Employee(String name, int monthlySalary) {
this.name = name;
this.monthlySalary = monthlySalary;
}
// annualSalary() method returns the annual salary of the employee as an int
public int annualSalary() {
return monthlySalary * 12;
}
// toString() method returns the employee name and monthly salary as a
// String in the format: name, monthly salary
public String toString() {
return "Name: " + name + "\t\tMonthly Salary: " + monthlySalary;
}
}
this()will make your constructors depend on the other constructors, but how "dangerous" that kind of dependency is, is debatable.Builderpattern.