被final修饰的变量不是相当于常量吗?
下面这段代码中
public class Coffee {
private static final long counter = 0;
private final long id = counter++;
public String toString(){
return getClass().getSimpleName()+" "+id;
}
}
既然id被final修饰,为什么可以把counter++赋值给id?
...全文
1459打赏收藏
final 关键字
被final修饰的变量不是相当于常量吗? 下面这段代码中 public class Coffee { private static final long counter = 0; private final long id = counter++; public String toString(){ return getClass().getSimpleName()+" "+id; } } 既然id被final修饰,为什么可以把counter++赋值给id?
public class Coffee {
private static final long counter = 0;
private final long id = counter++;
public String toString(){
return getClass().getSimpleName()+" "+id;
}
}
counter是long类型,普通数据类型;id也是long类型,普通数据类型。final修饰的变量只能被赋值一次,其值(引用也算是值的一种)不能被改变。
在"private final long id = counter++;"中:id=counter++这语句首先是把counter的值赋值给id,此时id=0,但是counter++会改变counter的值,前面已经给counter赋值了,因此这个程序过不了编译!情况如下:
E:\Demo\Test>javac Coffee.java
Coffee.java:3: 无法为最终变量 counter 指定值
private final long id = counter++; ^
1 错误
[Quote=引用楼主 chana1101 的回复:]
被final修饰的变量不是相当于常量吗?
下面这段代码中
public class Coffee {
private static final long counter = 0;
private final long id = counter++;
public String toString(){
return getClass().getSimpleName()+" "+id;……
[/Quote]