0

I have a doubt regarding the initialization of variables of a class. When usually declare a class with the variables and I initialize (even if they are final) I do it via the constructor.

For example:

class Example {
    private int a, b;
   
    public Example () {
        a = 5;
        b = 10;
    }

    // Methods
}

But you can also initiate immediately after the statement.

For example:

class Example {
    private int a = 5, b = 10;
   
    // Methods
}

What is the best way to initialize variables? What is the difference?

mikelplhts
  • 1,181
  • 3
  • 11
  • 32

2 Answers2

0
class Foo {
   String username = "user";
   String password = null;
}

is functionally equivalent to

class Foo {
    String username, password;
    Foo() { 
        username = "user";
        passowrd = null; 
    }
}

Consider however, a situation that at some later point you need to add another constructor:

public Foo(String password) {
    this.password = password;
}

Now, somebody calling new Foo("mypasswd") is risking to have username left uninitialized. If you initialize the member variables as they are declared, they will always be initialized, regardless of how the instance of the class was created (except for deserialization, that's a separate story!). If you initialize them in the default constructor, then all other constructors need to either call it explicitly or take care of initializing the variables themselves.

It is advisable to always give all variables some kind of an initial value when you declare them, to reduce the possibility of surprises and unpredictable behavior.

Dima
  • 39,570
  • 6
  • 44
  • 70
-1

The variables initialized the first way will get their values when the init<> method is run. The variable initialized in the second way will get their value when the constructor is executed. For simple use cases like this there is no effective difference, but if you have multiple constructors or "interesting" things happening with the object lifecycle, it can matter. There is no always-better way.

(One example of how you'd get different behavior is if a superclass' constructor - which must run before the subclass - used reflection to act based on the instance field variables somehow. This isn't a very common thing to need to happen, but it's an example of what I meant by "interesting"...)

BadZen
  • 4,083
  • 2
  • 25
  • 48
  • 1
    Not really. As you said yourself, superclass constructor is called before anything in the subclass, so, regardless of how subclass initializes its members, superclass constructor accessing them via reflection will always see them uninitialized. – Dima Jan 13 '15 at 02:40