多態 (電腦科學)

喺電腦科學上，多態簡單講係指一嚿嘢可以有多個唔同嘅樣。

繼承

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

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
   }
}

物件導向編程

參攷

物件導向編程