Search code examples
javafinalprivate-constructor

Private constructor and final instance variables


If you create a class with uninitialized final variables and a private default constructor, the compiler screams at you that you have uninitialized final variables. That's all well and dandy, except that the constructor is now just unreachable code. So is this just oversight from the Java creators or is there a logical, behind the scenes reason for this? Or is my assumption that the constructor is unreachable code wrong?


Solution

  • Well, the 'screaming' would occur regardless of the constructor access level (private/public/protected/package)... these issues are handled separately.

    On the one level, the compiler makes sure that IF constructor is (somehow, miraculously) invoked than all final variables are initialized.

    Then on a different level we worry about constructor reachability. Which is a bit more complex because obviously you could later add factory methods, and furthermore you could reach it with ugly reflection code using "setAccessible(true)"