(1) Javaのポリモフィズムのメリットや例をご紹介
(1-1) ポリモフィズムとは?
(1-2) サンプルプログラム
(1-3) ポリモフィズムのメリット
(1-4) 参考:ポリモフィズムの種類について
(1) Javaのポリモフィズムのメリットや例をご紹介
(1-1) ポリモフィズムとは?

(1-2) サンプルプログラム
public class IT0209_Polymorphism {
public static void main(String args[]) {
//Furits型の配列を作成
//この時、サブクラスのインスタンスはスーパークラス型に代入が可能
Fruit[] fr = {new Apple("青森県"),new Lemon("広島県"),new Melon("茨城県")};
for(int i=0; i<fr.length; i++) {
//同じcolorメソッドだが、オブジェクト(Apple,Lemon,Melon)によって異なる挙動を示す
fr[i].color();
}
}
}
//スーパークラス
class Fruit {
public void color() {
System.out.println("This is some kind of Fruits");
}
}
//Fruitsのサブクラス#1
class Apple extends Fruit {
private String origin;
//コンストラクタ
public Apple(String origin) {
this.origin = origin;
}
//オーバーライド
public void color() {
System.out.println("This is an APPLE made in "+origin+" and the color is RED");
}
}
//Fruitsのサブクラス#2
class Lemon extends Fruit {
private String origin;
//コンストラクタ
public Lemon(String origin) {
this.origin = origin;
}
//オーバーライド
public void color() {
System.out.println("This is an LEMON made in "+origin+" and the color is YELLO");
}
}
//Fruitsのサブクラス#3
class Melon extends Fruit {
private String origin;
//コンストラクタ
public Melon(String origin) {
this.origin = origin;
}
//オーバーライド
public void color() {
System.out.println("This is an MELON made in "+origin+" and the color is GREEN");
}
}
(図121)実行結果
7行目のforループでFruit型の配列をループして、各要素のcolorメソッドを呼び出しています。各要素のオブジェクトが異なり実装も違うので、違った結果になります。

(1-3) ポリモフィズムのメリット
(1-4) 参考:ポリモフィズムの種類について
今回は深くは触れませんが、ポリモフィズムには大きく分けて2つの種類があります。概要だけ簡単に紹介いたします。