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();
}
}
Why this returns Kind: falcon, Id: 2; Kind: eagle, Id: 2 I really can’t figure it out? birds[0] and birds[1] have different instances, how they have ID of 2? Why it’s not 1 and 1?
This is because the
idis static, and therefore is shared among all instances of the class.What you probably wanted is something along these lines:
Please note that this may be overly simplistic, and not suitable in multithreaded environments.