4

Suppose I have

class MyObject
{
    Object object1 = new Object();
    Object object2;

    public MyObject()
    {
        object2 = new Object();
    }

    public MyObject(Object object2)
    {
        this.object2 = object2;
    }

    public MyObject(Object object1, Object object2)
    {
        this.object1 = object1;
        this.object2 = object2;
    }
}

When does object1 get initialized? Before object2, after object2, depends?

What happens if I have a constructor that conflicts with the global definition of object1, e.g. in the third constructor above. Which value does object take?

This isn't causing me any problems but I just wanted to understand the language a bit better. I like to know these little things so that I could potentially make use of them later on.

Bhavik Ambani
  • 6,557
  • 14
  • 55
  • 86
nullUser
  • 1,601
  • 1
  • 12
  • 29

2 Answers2

6
  • The variables are initialized to the default values for their type (0, null etc)

  • First the superclass constructor is called. If the superclass constructor calls any virtual methods overridden in this class, the override will see the default values, regardless of any variable initializers or initialization in the constructor body.

  • Then variable initializers are executed.

  • Then the constructor body is executed.

So if you change the value of a variable within the constructor body, any value set by the variable initializer will be overwritten. (The previous value could have been used in other chained constructors etc, of course.)

See section 12.5 of the JLS for more details.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

If you want to confirm behavior, use javap or a similar tool to inspect the bytecode. Though Jon is correct, refer to the specification as a first port of call.

Compiled from "MyObject.java"
class MyObject {
  java.lang.Object object1;

  java.lang.Object object2;

  public MyObject();
    Code:
       0: aload_0
       1: invokespecial #11               // Method java/lang/Object."<init>":()V
       4: aload_0
       5: new           #3                // class java/lang/Object
       8: dup
       9: invokespecial #11               // Method java/lang/Object."<init>":()V
      12: putfield      #13               // Field object1:Ljava/lang/Object;
      15: aload_0
      16: new           #3                // class java/lang/Object
      19: dup
      20: invokespecial #11               // Method java/lang/Object."<init>":()V
      23: putfield      #15               // Field object2:Ljava/lang/Object;
      26: return
Community
  • 1
  • 1
McDowell
  • 107,573
  • 31
  • 204
  • 267