When initializing variables in Java, developers can choose between initializing within the constructor or outside the constructor. This question explores the pros and cons of each approach.
Inside Constructor (Style 1):
<br>public class ME {</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">private int i; public ME() { this.i = 100; }
}
Outside Constructor (Style 2):
<br>public class ME {</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">private int i = 100; public ME() { }
}
Recommended Convention:
The recommended convention, as stated in the accepted answer, is Style 2 (initialization within the declaration). This style offers the following advantages:
Exceptions to the Convention:
Of course, there are exceptions where Style 1 is more suitable:
In general, Style 2 should be used whenever possible to enhance code readability and maintainability.
The above is the detailed content of Constructor vs. Declaration: Where Should I Initialize My Java Variables?. For more information, please follow other related articles on the PHP Chinese website!