I know there are several ways to initialize stuff at instance creation in Java, but I'm interested in the difference between the following 2 possibilities.
Case 1:
{
// common init code for all constructors
}
public MyType() {
super();
// specific init code
}
public MyType(Object arg) {
super(arg);
// specific init code
}
Case 2:
public MyType() {
super();
init();
// specific init code
}
public MyType(Object arg) {
super(arg);
init();
// specific init code
}
private void init() {
// common init code for all constructors
}
I believe these 2 cases are equivalent in terms of code. I think the first is faster because there is 1 less method call, but on the other hand it might be confusing for someone who is not very knowledgeable about initialization.
Is there another difference that I have missed that could lead us to choose one over the other? Which option should I use preferably?
Note: the init()
method is private, and I know a different visibility could lead to initialization bugs (when subclassing), this is not the point.