継承を用いたクラスの定義
元の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クラスを継承する。