What is the difference between defining and initialising the member variables in the beginning of the class definition, and defining the member variables first and initialising the member variables in the constructor?
Say, for example:
public class Test { private int foo = 123; private boolean flag = false; public void fooMethod() {...} }
Versus:
public class Test { private int foo; private boolean flag; public Test() { foo = 123; flag = false; } public void fooMethod() {...} }
Thanks in advance.
Const member variables must be initialized. A member initialization list can also be used to initialize members that are classes. When variable b is constructed, the B(int) constructor is called with value 5. Before the body of the constructor executes, m_a is initialized, calling the A(int) constructor with value 4.
If your variable is an instance variable and not a class variable you must initialize it in the constructor or other method.
Yes, you can also initialize these values using the constructor.
It makes sense to initialize the variable at declaration to avoid redundancy. It also makes sense to consider final variables in such a situation. If you know what value a final variable will have at declaration, it makes sense to initialize it outside the constructors.
In your example, the only difference is when they are initialized. According to the JLS, instance variables are initialized before the constructor is called. This can become interesting when you have super classes to deal with, as the initialization order isn't always so obvious. With that, keep in mind "super" instance variables will still be initialized when no explicit super constructor is called.
The difference is the order in which they are initialized / set.
Your class member variables will be declared / set before your constructor is called. My personal preference is to set them in the constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With