Ersel Aker Ersel Aker - 7 months ago 22
Java Question

Object oriented java sample exam

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();
}
}


This is a question from a sample exam, The output is asked and the correct answer is
Kind: falcon, Id: 2; Kind: eagle, Id: 2;

I didn't understand why id is 2 and it is same for both instances. Can you please explain?

Answer

Since the id field is static, it will have the same value throughout (and outside of) all instances of Bird.

After creating two Bird objects, the constructor will have been called twice, therefore the id will be 2.

See: Understanding Instance and Class Members

Comments