ポリモーフィズム: 多態性

同じメソッド呼び出しで異なる振る舞い。OOP の核心。

ポリモーフィズム
同じ操作で異なる振る舞い。
オーバーライド
親メソッドを子で上書き。
動的ディスパッチ
実行時に呼ぶメソッドを決定。
Universal Remote

ポリモーフィズムは「万能リモコン」。 同じ「電源ボタン」を押しても、TVならTVがつき、エアコンならエアコンがつく。 **同じインターフェース**で**異なる振る舞い**。

ポリモーフィズム

Override, Dynamic dispatch
// 親クラス
public class Animal {
public void speak() {
System.out.println("...");
}
}
// 子クラス
public class Dog extends Animal {
@Override
public void speak() {
System.out.println("Woof!");
}
}
public class Cat extends Animal {
@Override
public void speak() {
System.out.println("Meow!");
}
}
// ポリモーフィズム:親型で異なる振る舞い
Animal[] animals = {new Dog(), new Cat()};
for (Animal a : animals) {
a.speak(); // Woof!, Meow!
}
実行結果
Woof!\nMeow!
Bad
// ❌ Bad: 型チェックの連鎖
if (animal instanceof Dog) {
((Dog) animal).bark();
} else if (animal instanceof Cat) {
((Cat) animal).meow();
}
Good
// ✅ Good: ポリモーフィズムで統一
animal.speak(); // 各クラスで適切にオーバーライド

パターン

Interface, Pattern matching
// インターフェースでのポリモーフィズム
interface Drawable {
void draw();
}
class Circle implements Drawable {
public void draw() { System.out.println("○"); }
}
class Square implements Drawable {
public void draw() { System.out.println("□"); }
}
// 統一的に処理
List<Drawable> shapes = List.of(new Circle(), new Square());
for (Drawable d : shapes) {
d.draw(); // ○, □
}
// パターンマッチング (Java 16+)
if (obj instanceof String s) {
System.out.println(s.length()); // キャスト不要
}
// switch でのパターンマッチング (Java 21)
String result = switch (obj) {
case Integer i -> "Integer: " + i;
case String s -> "String: " + s;
default -> "Unknown";
};
Tip: instanceof の連鎖はポリモーフィズムで置き換える。

合格ライン

親型で子オブジェクトを扱える
instanceof の代わりにポリモーフィズムを使える

参考リンク

演習課題

課題1: ポリモーフィズム
親クラス型の変数で子クラスを扱ってください。
課題2: instanceof 置換
instanceof を使わずにポリモーフィズムで設計してください。

次のステップ