共計 413 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,父類可以引用指向子類對象,這種特性稱為多態性。具體實現方式如下:
- 定義一個父類和一個子類:
class Parent {public void display() {System.out.println("This is the parent class.");
}
}
class Child extends Parent {@Override
public void display() {System.out.println("This is the child class.");
}
}
- 創建子類對象,并用父類引用指向它:
Parent parent = new Child();
parent.display();
在上面的代碼中,父類 Parent 的引用 parent 指向子類 Child 的對象。當調用 display() 方法時,實際上會調用子類 Child 中的 display() 方法,因為多態性允許父類引用指向子類對象,并且調用子類重寫的方法。
丸趣 TV 網 – 提供最優質的資源集合!
正文完