Java Member Initialization

What's the difference between:

public class A
{
    private int x = 1;
    A() {}
}

and

public class A
{
    private int x;
    A() { x = 1; }
}

if any?

+5
source share
8 answers

If you ask from a practical point of view, the difference is that with the second form of initialization you will have to repeat it for each constructor written, do you need to write a lot of overloaded constructors.

+3
source
  • In the second case, you repeat the initialization x = 0, since it is an instance variable, so by default it will be initialized to 0.
  • It may be a difference if there are several designers. I do not think about other differences.
+2
source

JLS 12.5:

, , , , , , .

:

, , :

  • .

  • ( ), , . , ; 5.

  • ( ). , Object, ( ). , . , . , 4.

  • , , , . , , . , 5. ( , , .)

  • . , . .

, JVM x ( ) (0 x). A , .

+2

1/ - - , .

2/ x, . .

+2

. -scope , , . int 0. .

, .

+1

,

public class A
{
    private int x;
    A(String something) {  }
}

, (), x, . , .

0

  • 0, - 0.

  • no arg, .

, 0. , - , 0, x=20;

0

.

x , , "new A();" .

Seeing that x is not static, the processing is virtually the same, however in JLS there are nuances that you should be aware of, especially if A, for example, extends another class.

If you did something with x in the constructor before it was initialized (as in example 2), for example. int b = x; don't expect b to be 1. Outside the top of your head, you will either receive an error / warning message in the compiler, or b will be zero.

0
source

All Articles