Object oriented java sample exam

2019-02-28 00:52发布

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?

标签: java oop
6条回答
\"骚年 ilove
2楼-- · 2019-02-28 01:12

Because the id is static. That means that is a "Class variable/field" and there is only one per Class. All the instances of that Class share it the same id (indeed calling it "id" feels kinda weird).

See here

查看更多
一夜七次
3楼-- · 2019-02-28 01:13

static variables are shared across objects unlike instance variables. So when this executes

birds[0] = new Bird("falcon");

the id increments to 1. After that the below is executed incrementing it to 2

birds[1] = new Bird("eagle");
查看更多
太酷不给撩
4楼-- · 2019-02-28 01:21

because we are calling toString in the end. When toString takes value of id to return its always 2. Better to print references one by one .

查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-02-28 01:26

in addition to static variable 'for' loop only put

System.out.print(birds[i]);

not

System.out.println(birds[i]);

so until end of execute 'for' loop it print only one Line because 'for' loop have not {} bracket it loop only one line

查看更多
神经病院院长
6楼-- · 2019-02-28 01:32

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

查看更多
Explosion°爆炸
7楼-- · 2019-02-28 01:34

because here private static int id = 0; id is declared static or class variable. Static variables are class variable they are not initialized or created every time an object is created.

So, only one copy of static variable exist. No, new copies are created when object are created using new operator.

查看更多
登录 后发表回答