Java – which is better to assign attribute values in constructors or classes?
Are there any differences between instantiations of the following types?
If not, what are the best practices?
"In class":
class A { boolean b = true; public A(){ } }
In constructor:
class B { boolean b; public B(){ b = true; } }
Variable types are for example only The only difference I see is that when the property is a complex type (class), the constructor depends on the value given to the constructor containing the class:
class A { B b; public A(String s){ b = new B(s); } }
Solution
In fact, they are equivalent But from a readability point of view, the first one is more readable In addition, when someone navigates from the IDE to a variable declaration (for example, Ctrl + click in eclipse), it's easy to see the default value
View the contents of the official tutorial –
Therefore, when the process is simple, you can easily use simple single line initialization technology Constructor is a feasible method for complex initialization selection