Uninitialized class members in Java do not issue any compiler errors. local variables however do. Why?

后端 未结 5 1275
挽巷
挽巷 2020-12-01 21:14

Consider the following code snippet in Java. It won\'t compile.

package temppkg;

final public class Main
{
    private String x;
    private int y;

    pri         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 21:44

    When in doubt, check the Java Language Specification (JLS).

    In the introduction you'll find:

    Chapter 16 describes the precise way in which the language ensures that local variables are definitely set before use. While all other variables are automatically initialized to a default value, the Java programming language does not automatically initialize local variables in order to avoid masking programming errors.

    The first paragraph of chapter 16 states,

    Each local variable and every blank final field must have a definitely assigned value when any access of its value occurs....A Java compiler must carry out a specific conservative flow analysis to make sure that, for every access of a local variable or blank final field f, f is definitely assigned before the access; otherwise a compile-time error must occur.

    The default values themselves are in section 4.12.5. The section opens with:

    Each class variable, instance variable, or array component is initialized with a default value when it is created.

    ...and then goes on to list all the default values.

    The JLS is really not that hard to understand and I've found myself using it more and more to understand why Java does what it does...after all, it's the Java bible!

提交回复
热议问题