汎化(Generalization)
具体的なクラスを抽象化したクラスの関係が汎化である.逆に,抽象化されたクラスを具体的にする関係が特化である.
上記の図では,StudentやTeacher,Actorに共通する部分を持つように,抽象的なPersonクラスが定義されている.すなわち,StudentやTeacher,Actorを汎化してPersonが定義されている.
逆に,抽象的なPersonを具体化して個別具体的な要素や振る舞いが含まれて,Student,Teacher,Actorが定義されている.すなわち,Personを特化して,StudentやTeacher,Actorが定義されている.
『「学生」は「人」である』,『「先生」は「人」である』,と表現することができることから,汎化の関係は「is-a」関係と呼ぶ.一般に,「サブクラス」 is-a 「スーパークラス」の形である.
厳密に考えると,『「学生」は「人」の一種である』と表現した方が適切かもしれない.スーパークラスは,サブクラスを汎化しているので,サブクラスを抽象化してスーパークラスが定義されている.
public class Student extends Person { int studentNumber; Student(String name, int studentNumber) { super(name); this.studentNumber = studentNumber; } public void selfIntroduction() { System.out.print(studentNumber + "番の"); super.selfIntroduction(); } public void studying() { System.out.println("勉強します"); } }
public class Teacher extends Person { String position; Teacher(String name, String position) { super(name); this.position = position; } public void selfIntroduction() { System.out.print(position + "の"); super.selfIntroduction(); } public void teaching() { System.out.println("授業をします"); } }
public class Person { String name; Person(name) { this.name = name; } public void selfIntroduction() { System.out.print(name+ "です"); }
public class Actor extends Person { String realName; Actor(String actorName,String realName) { super(actorName); this.realName = realName; } public void selfIntroduction() { System.out.print("本名" + realName + "の"); super.selfIntroduction(); } public void acting() { System.out.println("演技します"); } }
public class Main { public static void main(String args[]) { System.out.println("===学生==="); Student ikoma = new Student("生駒",446); ikoma.selfIntroduction(); ikoma.studying(); System.out.println("===教授==="); Teacher akimoto = new Teacher("秋元","教授"); akimoto.selfIntroduction(); akimoto.teaching(); System.out.println("===演者==="); Actor yuka = new Actor("岡部広子","優香"); yuka.selfIntroduction(); yuka.acting(); } }
実行すると,以下のようになる.
===学生=== 446番の生駒です 勉強します ===教授=== 教授の秋元です 授業をします ===演者=== 本名優香の岡部広子です 演技します
汎化したクラスのみではインスタンス化できない場合,そのクラスを抽象クラスと呼ぶ.つまり,抽象クラスは,特化したサブクラスを持つ必要がある.