0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

✅ 完璧!ポリモーフィズム完全動作!🎉
結果の分析

=== 1. 基本 ===
Animal a1 = new Dog(...) → Dog の toString() が動く ✅
Animal a2 = new Cat(...) → Cat の toString() が動く ✅
→ 同じ型なのに違う動作!

=== 2. 配列 ===
Animal[] に Dog も Cat も混在 ✅
同じ for ループで全部処理 ✅
→ ポリモーフィズム最大のメリット!

=== 3. 引数 ===
printAnimalInfo(Animal) に Dog も Cat も渡せる ✅
→ メソッドを1つ書くだけで両方対応!

=== 4. instanceof ===
中身が Dog → bark() ✅
中身が Cat → meow() ✅
→ 必要な時だけ固有メソッドを呼べる!
🔑 ポリモーフィズムのメリットまとめ

ポリモーフィズムなし ポリモーフィズムあり
───────────────── ─────────────────
Dog[] dogs = {...} Animal[] animals = {...}
Cat[] cats = {...}
for (Animal a : animals) {
for (Dog d : dogs) { a.eat();
d.eat(); }
}
for (Cat c : cats) { → 1つのループで済む!
c.eat(); → 新しい動物追加も簡単!
}

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?