多態 (電腦科學)
閱讀設定
喺電腦科學上,多態(英文:polymorphism)簡單講係指一嚿嘢可以有多個唔同嘅樣。
繼承
[編輯]睇埋:繼承 (電腦科學)
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
}
}
睇埋
[編輯]參攷
[編輯]- ↑ Polymorphism explained simply!. Medium.