Reputation: 37749
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.
Upvotes: 1
Views: 1669
Reputation: 361
In short, init code in first case will be called before constructor, in second - after. Check out this question.
General rule is to avoid constructions like theese and use static-factory-methods instead.
Order might matter then calling this() instead of super(): Consider code:
public class InitOrderTest {
static class Super {
Super() {
System.out.println("Super constructor");
}
}
static class Puper extends Super {
{
System.out.println("Code block");
}
Puper() {
this("Self constructor");
init();
}
public Puper(String inner) {
System.out.println(inner);
}
private void init() {
System.out.println("Init call");
}
}
public static void main(String[] args) {
new Puper();
}
}
It prints:
Super constructor
Code block
Self constructor
Init call
Upvotes: 0
Reputation: 213351
Maybe the first is faster because there is 1 less method call, but I think it is less readable.
I wouldn't even consider efficiency here as it would make just a minor difference of method call. But why do you think it is less readable? It's a well known feature of Java language.
Which option should I use preferably?
The benefit of first approach is, you've to write less code. And there is slight chance of human error in second approach. Generally you would use instance initializer block when you want the initialization to be done in every constructor. That saves you from explicitly writing same code in all constructor. With the other approach, you have to remember to invoke init()
method from all the constructors.
But if you want some initialization to be part of some constructor, then the second approach might be useful. But that is very rare IMO.
Upvotes: 1