Java super 关键字

实例

使用 super 调用 Dog 的超类(subclass):

  1. class Animal { // Superclass (parent)
  2. public void animalSound() {
  3. System.out.println("The animal makes a sound");
  4. }
  5. }
  6. class Dog extends Animal { // Subclass (child)
  7. public void animalSound() {
  8. super.animalSound(); // Call the superclass method
  9. System.out.println("The dog says: bow wow");
  10. }
  11. }
  12. public class Main {
  13. public static void main(String[] args) {
  14. Animal myDog = new Dog(); // Create a Dog object
  15. myDog.animalSound(); // Call the method on the Dog object
  16. }
  17. }

定义与用法

super 关键字指的是超类(父)对象。

它用于调用超类方法,并访问超类构造函数。

super 关键字最常用的用法是消除具有相同名称的方法的超类和子类之间的混淆。

要理解 super 关键字,您应该对 Java 的 继承性多态性 有基本的了解。


关联页面

Java 继承 中学习更多关于继承(子类和超类)的知识。

Java 多态 中学习更多关于多态性的知识。

分类导航