为什么最终变量不总是常量表达式? [英] Why isn't a final variable always a constant expression?

查看:136
本文介绍了为什么最终变量不总是常量表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中:

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

为什么会出现此错误? a最终变量不是编译时常量表达式,因此在赋值期间隐式地缩小为字节吗?

Why do I get this error? Isn't a final variable compile time constant expression and hence implicitly narrowed to byte during the assignment?

换句话说,上面的代码不等同于:

In other words isn't the above code equivalent to:

final int a=2;
byte b=a;

推荐答案

编译器不是那么聪明.

我们可以知道该值始终为2.但是如果我们有类似的东西怎么办?

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.

这篇关于为什么最终变量不总是常量表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆