LoginSignup
0
0

More than 3 years have passed since last update.

java(継承)

Last updated at Posted at 2020-05-20

継承を用いたクラスの定義

元のHeroクラス

Hero.java
public class Hero {
  String name = "勇者";
  int hp = 100;
  //戦う
  public void attack(Matango m) { 
    System.out.println(this.name + "攻撃!");
    m.hp -= 5;
    System.out.println("5ポイントダメージをあたえた!");
  }
  //逃げる
  public void run() {
    System.out.println(this.name + "は逃げ出した!");
  }
}

継承を使わないSuperHeroクラス

SuperHero.java
public class SuperHero {
  String name = "勇者";
  int hp = 100;
  boolean flying;
  //戦う
  public void attack(Matango m) { 
    System.out.println(this.name + "攻撃!");
    m.hp -= 5;
    System.out.println("5ポイントダメージをあたえた!");
  }
  //逃げる
  public void run() {
    System.out.println(this.name + "は逃げ出した!");
  }
  //飛ぶ
  public void fly() {
    this.flying = true;
    System.out.println("飛び上がった!");
  }
  //着地する
  public void land() {
    this.flying = false;
    System.out.println("着地した!");
  }
}

戦う、逃げるが重複している。
Heroクラスを変更した場合、SuperHeroクラスも変更しないといけない。

継承を使用したSuperHeroクラス

SuperHero.java
public class SuperHero extends Hero{
  boolean flying;
  //飛ぶ
  public void fly() {
    this.flying = true;
    System.out.println("飛び上がった!");
  }
  //着地する
  public void land() {
     this.flying = false;
     System.out.println("着地した!");
  }
}

extend 元となるクラス名でHeroクラスを継承する。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0