Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize member variables in the beginning of class definition or in constructor?

Tags:

java

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.

like image 812
blaze Avatar asked Aug 24 '11 00:08

blaze


People also ask

Are member variables initialized before constructor?

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.

Where should you initialize variables in a class?

If your variable is an instance variable and not a class variable you must initialize it in the constructor or other method.

Can we initialize variable in constructor?

Yes, you can also initialize these values using the constructor.

Why do we initialize variable in 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.


2 Answers

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.

like image 132
Jeremy Avatar answered Oct 16 '22 01:10

Jeremy


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.

like image 33
tsells Avatar answered Oct 16 '22 01:10

tsells