Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it true that the assigned final object field may still be null inside a constructor?

Is it true that the assigned final object field may still be null inside a constructor?

class MyClass {
  private final Object obj = new Object();
  public MyClass() {
    System.out.println(obj); // may print null?
  }
}

if yes, isn't this a bug?

like image 564
The Student Avatar asked Mar 30 '10 17:03

The Student


1 Answers

As discussed by other answers, no, that can not happen. With an assigned final static field, however, it can.

class MyClass {
  private static MyClass myClass = new MyClass();
  private static final Object obj = new Object();
  public MyClass() {
    System.out.println(obj); // will print null once
  }
}
like image 122
ILMTitan Avatar answered Oct 12 '22 21:10

ILMTitan