class text0{
private static long counter=0;
private final long id=counter++;
public text0(){
System.out.println("id="+id+" counter"+counter);
}
}
public class Damo0 { public static void main(String[] args) {
new text0();
new text0();
new text0();
new text0();
new text0();
new text0();
new text0();
}}
output:id=0 counter1
id=1 counter2
id=2 counter3
id=3 counter4
id=4 counter5
id=5 counter6
id=6 counter7
final不是只可以赋常量值吗?

解决方案 »

  1.   

    id 的值没有变。每次的new text();都相当于给id一个固定的值,变的只是count;
      

  2.   

       static long count=0中的count在类的静态区域中,在类加载的过程中只分配一个static区域,而在生成7个test对象的时候count的值每次都+1,而每个test对象的final int id的值是就是当前的count+1,id的值是不同,是因为对象也不同而已...
      

  3.   

    这道题 真的会让人迷惑 但细想之下不难分析 。 首先 static 的变量 是类变量 即所有的对象共享 ,所以 多次 创建这个 对象 会用用一个static的变量 自然 他的值也就跟着 ++了,final的变量是可以只赋常量值 如 i=2  final int j = i 也是可以的 ,上面也同理 final的变量不能改变的意思说 ,但是可以赋值一次呀 ,上面的相当于赋初始值 一句话 不管用什么方式给final的变量赋初始值,以后就不能再赋值了 
      

  4.   

    每个test0对象都有一个id,但是counter只有一个,所有test0对象共用
    id的值赋值之后并没有变,变的是counter
      

  5.   

    counter 在变,当ID取得counter后,就不再变了。
    你可以试试改变id, 一定会报错