public class Bird
{
private static int id = 0;
private String kind;
public Bird(String requiredKind)
{
id = id + 1;
kind = requiredKind;
}
public String toString()
{
return "Kind: " + kind + ", Id: " + id + "; ";
}
public static void main(String [] args)
{
Bird [] birds = new Bird[2];
birds[0] = new Bird("falcon");
birds[1] = new Bird("eagle");
for (int i = 0; i < 2; i++)
System.out.print(birds[i]);
System.out.println();
}
}
我知道因为 int 是静态的,所以两个 id 都是相同的,但无法弄清楚为什么输出是 2 而不是 1?
运行时输出:
Kind: falcon, Id: 2; Kind: eagle, Id: 2;