Why must a final variable be initialized before constructor completes?

后端 未结 9 489
暖寄归人
暖寄归人 2020-12-01 03:38

Why must a final variable be initialized before constructor completes?

public class Ex
{
  final int q;
}

When I compile this code I get er

9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 04:12

    The language specification contains specific guarantees about the properties of final variables and fields, and one of them is that a properly constructed object (i.e. one whose constructor finished successfully) must have all its final instance fields initialized and visible to all threads. Thus, the compiler analyzes code paths and requires you to initialize those fields.

提交回复
热议问题