good_evening
good_evening

Reputation: 21759

Why do they have the same ID?

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

Answers (3)

Manish
Manish

Reputation: 3968

  1. Static fields are "per class" not "per instance".
  2. When you create the first object, the constructor is called and id becomes 1(0+1).
  3. When you create the second object, the constructor is called and id becomes 2(1+1)

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

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

Ramon Saraiva
Ramon Saraiva

Reputation: 518

Your id field is static, so all your instances will have the same id

Upvotes: 1

Related Questions