Java 抽象クラス


abstract class Score {
  private String subject;
  protected int score;

  Score(String subject, int score) {
    this.subject = subject;
    this.score = score;
  }

  protected abstract String getResult();

  String getScoreString() {
    return this.subject + ", " + this.score + ", " + this.getResult();
  }
}

class MathScore extends Score {
  MathScore(int score) {
    super("Math", score);
  }

  @Override
  protected String getResult() {
    System.out.println("MathScore method");
    return this.score >= 50 ? "Pass" : "Fail";
  }
}

class EnglishScore extends Score {
  EnglishScore(int score) {
    super("English", score);
  }

  @Override
  protected String getResult() {
    System.out.println("EnglishScore method");
    return this.score >= 70 ? "Pass" : "Fail";
  }
}

class User {
  private String name;
  private Score score;

  User(String name, Score score) {
    this.name = name;
    this.score = score;
  }

  String getUserString() {
    return this.name + ", " + this.score.getScoreString();
  }
}

public class MyApp {
  public static void main(String[] args) {
    User user1 = new User("Taro", new MathScore(70));
    User user2 = new User("Jiro", new EnglishScore(80));

    System.out.println(user1.getUserString());
    System.out.println(user2.getUserString());
  }
}

投稿者: chosuke

趣味はゲームやアニメや漫画などです

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です