Home >Java >javaTutorial >Java Initializer Placement: Inside or Outside Constructors?
Initializer Placement in Java: Inside or Outside Constructors
When transitioning from C to Java, Java developers often face a decision regarding variable initialization: should it be inside or outside constructors?
Inside Constructors:
public class ME { private int i; public ME() { this.i = 100; } }
This approach initializes the variable explicitly within the constructor. It allows for initialization values that vary between constructors.
Outside Constructors:
public class ME { private int i = 100; public ME() { } }
Here, the variable is initialized directly in its declaration. This provides a default initialization that applies to all constructors.
Recommendation:
The preferred style is to initialize variables outside constructors. This offers several advantages:
Of course, if different constructors require different initialization values or calculations, then initialization should occur within the constructor. However, the outside constructor approach is generally considered more efficient and elegant for consistent default values.
The above is the detailed content of Java Initializer Placement: Inside or Outside Constructors?. For more information, please follow other related articles on the PHP Chinese website!