package com.pp;
class Count{
private int serial;
static int counter=0;
Count(){
counter++;
serial=counter;
}
int getSerial(){
return serial;
}
int getCounter(){
return counter;
}
}
public class 例子 {
public static void main(String args[]){
Count c1=new Count();
Count c2=new Count();
System.out.println("c1的serial值:"+c1.getSerial() );
System.out.println("c1的count值:"+c1.getCounter() );
System.out.println("c2的serial值:"+c2.getSerial() );
System.out.println("c2的count值:"+c2.getCounter() );
}
}
c1的serial值:1
c1的count值:2
c2的serial值:2
c2的count值:2
Count c1=new Count();
Count c2=new Count();
因为你首先连续调用了2次new,也就是构造函数调用了2次
所以之后输出无论c1还是c2的count都是2。
你要看到1,可以写
Count c1=new Count();
System.out.println("c1的serial值:"+c1.getSerial() );
System.out.println("c1的count值:"+c1.getCounter() );
Count c2=new Count();
System.out.println("c2的serial值:"+c2.getSerial() );
System.out.println("c2的count值:"+c2.getCounter() );