Reputation: 21759
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?
Upvotes: 0
Views: 103
Reputation: 3968
Upvotes: 0
Reputation: 726809
This is because the id
is static, and therefore is shared among all instances of the class.
What you probably wanted is something along these lines:
public class Bird {
private static last_id = 0;
private int id ;
private String kind;
public Bird(String requiredKind) {
id = last_id++;
kind = requiredKind;
}
// ...
}
Please note that this may be overly simplistic, and not suitable in multithreaded environments.
Upvotes: 5
Reputation: 518
Your id field is static, so all your instances will have the same id
Upvotes: 1