エンジニア成長日記 swaponQ

コンピュータサイエンス専攻の一般人のブログです。

新・明解 Java 入門 演習 10-2 解答

Hello, Terminal!swaponQです!

今回は演習 10-2 に取り組んでいこうと思います。

  • 演習 10-2

演習10-1で作成したクラスIdを、以下のように変更したクラスExIdを作成せよ。
インスタンスを生成するたびに識別番号をnずつ増やして与える(nは正の整数)。nの値は、指定されない限り1とするが、メソッドを通じて取得・変更できるようにする。

・ExIdTester.java

class ExId {
  static int counter = 0;

  private int id;
  static int n = 1;

  static void changeN(int i) {
    n = i;
  }

  public ExId() {
    counter += n;
    id = counter;
  }

  public int getExId() {
    return id;
  }

  static int getMaxExId() {
    return counter;
  }
}

public class ExIdTester  {

  public static void main(String[] args) {

    ExId a = new ExId();
    ExId b = new ExId();
    ExId.changeN(4);
    ExId c = new ExId();
    ExId d = new ExId();

    System.out.println("aの識別番号: " + a.getExId());
    System.out.println("bの識別番号: " + b.getExId());
    System.out.println("cの識別番号: " + c.getExId());
    System.out.println("dの識別番号: " + d.getExId());

    System.out.println("Id.counter = " + ExId.counter);
    System.out.println("a.counter = " + a.counter);
    System.out.println("b.counter = " + b.counter);
    System.out.println("c.counter = " + c.counter);
    System.out.println("d.counter = " + d.counter);
    System.out.println("MaxId = " + ExId.getMaxExId());
  }
}


・実行結果

aの識別番号: 1
bの識別番号: 2
cの識別番号: 6
dの識別番号: 10
Id.counter = 10
a.counter = 10
b.counter = 10
c.counter = 10
d.counter = 10
MaxId = 10

今回は以上です。お疲れ様でした!
次回は演習 10-3 です。

Goodbye, Terminal… swaponQでした!