-1

Consider the following example:

public class Constructor
{
     Constructor(int i)
     {
            System.out.println(i);
     }
}

public class Test
{

       Constructor c1 = new Constructor(1);

       Constructor c2 = new Constructor(2);

       public static void main(String[] args)
       { 
           new Test();
       }
}

This outputs:

1
2

Please explain why this happens and whether this behavior is consistent.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
Jerry_W
  • 125
  • 5
  • http://stackoverflow.com/questions/804589/use-of-initializers-vs-constructors-in-java – Yashar Panahi May 06 '17 at 04:26
  • Read the Fine Manual: http://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.5 – Lew Bloch May 06 '17 at 04:44
  • 3
    What's the actual question? – Adam May 06 '17 at 04:45
  • 2
    You should avoid the use of type names for custom types that match Java API type names, _especially_ names from `java.lang` and its subpackages, _especially_ especially well-known and widely used type names like `Constructor`. – Lew Bloch May 06 '17 at 04:48

1 Answers1

0

The initializers for static and instance fields are class are executed in the order that they appear in the source code.

In your example, the c1 declaration is before the c2 declaration, so it is executed first, and indicated by the output you see.

Why?

  1. Because the JLS says so:

    "4) Execute the instance initializers and instance variable initializers for this class, assigning the values of instance variable initializers to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class."

    (If that doesn't make sense to you, refer to the JLS to read the sentence in its context.)

  2. Because it makes sense to do it that way:

    • an unspecified order of initialization would be bad for code portability,
    • any other order (e.g. reverse order, lexical order) would be counter-intuitive.
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • but ponit Class Test "new Test()" not Class Constructor – Jerry_W May 06 '17 at 05:45
  • Yes. But `Test` declares `c1` and `c2` and initializes them using `new Constructor(...)`. My answer explains *what happens* when you `new Test()`. And what happens is that those two `Constructor` instances are created. – Stephen C May 06 '17 at 06:06