I'm new Java and are currently reading a course at university. We're using Java programming early objects as course literature. I have a question about constructors for new objects. The book states very clearly "Even though it’s possible to do so, do not call methods from constructors."
Is this for all methods, period? I understand the problem with calling the class own instance method from constructor. But helper methods, etc?
I made up a small example.
Here is an example of a class that needs one integer in its constructor. The integer needs to be greater than one.
Would this be acceptable? If not, I guess you can't use any of Java Math util function or anything like that in the constructor?
public class TestClass {
private int number;
// Only allow construction if number is greater than one
TestClass(int number) {
if (NumberUtils.isGreaterThanOne(number)) {
this.number = number;
} else {
throw new IllegalArgumentException("Number must be above 1");
}
}
}
public class NumberUtils {
// Helper method to check if number is greater than one
public static boolean isGreaterThanOne(int number) {
return number > 1;
}
}
TestClassobject with an invalid number, so throwing this exception (and call the check method before) is right and good.this) or even passing that instance as an argument to another method can be a problem, since the instance is eventually not fully initialized at that moment.