面向对象的Java示例考试 [英] Object oriented java sample exam

查看:50
本文介绍了面向对象的Java示例考试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是样本考试中的一个问题,要求输出,正确答案是 种类:猎鹰,ID:2;种类:鹰,Id:2;

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;

我不明白为什么id是2,并且两个实例都相同.你能解释一下吗?

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

推荐答案

由于id字段是静态的,因此在Bird的所有实例中(以及外部)都将具有相同的值.

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

在创建两个Bird对象之后,该构造函数将被调用两次,因此id将为2.

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

请参阅:了解实例和类成员

这篇关于面向对象的Java示例考试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆