電腦科學上,多態英文polymorphism)簡單講係指一嚿嘢可以有多個唔同嘅樣。

繼承

編輯

物件導向編程成日會用到嘅繼承功能會做到多態[1]

class Person {    
   public void teach(){
      System.out.println("Person can teach");
   }
}

class Teacher extends Person {
   public void teach() {
      System.out.println("Teacher can teach in a school");
   }
}

public class TestTeacher {
   public static void main(String args[]) {
      Person person = new Person(); //Person reference and object
      Person another_person = new Teacher(); //Person reference, Teacher object
      Teacher teacher = new Teacher(); //Teacher reference and obj.
      person.teach();//output: Person can teach
      // Here you can see Teacher object's method is executed even-
      // -though the Person reference was used  
      another_person.teach();//output: Teacher can teach in a school
      teacher.teach();//output: Teacher can teach in a school
   }
}

睇埋

編輯

參攷

編輯