Why isn't a final variable always a constant expression?

前端 未结 3 1512
后悔当初
后悔当初 2020-12-29 17:57

In the below code:

final int a;
a=2;
byte b=a;   // error: possible loss of precision

Why do I get this error? Isn\'t a final

3条回答
  •  遥遥无期
    2020-12-29 18:59

    The compiler isn't that smart.

    We can tell that the value will always be 2. But what if we had something like this?

    class ABC{
        final int a;
    
        public ABC(){
           if(Math.random() < .5){
              a = 2;
           }
           else{
              a = 12345;
           }
    
           byte b = a;
        }
    }
    

    The compiler is not smart enough to tell these two cases apart, so it gives you an error instead.

提交回复
热议问题