多態 (電腦科學)
繼承
編輯睇埋:繼承 (電腦科學)
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.