首页 > 文章列表 > Java中的super关键字

Java中的super关键字

继承(Inheritance) super(超类) 重写(override)
312 2023-09-07

  • super 变量引用直接父类实例。
  • super 变量可以调用直接父类方法。
  • super() 充当直接父类构造函数,并且应该位于子类构造函数中的第一行。

调用重写方法的超类版本时,使用 super 关键字。

示例

现场演示

class Animal {
   public void move() {
      System.out.println("Animals can move");
   }
}
class Dog extends Animal {
   public void move() {
      super.move(); // invokes the super class method
      System.out.println("Dogs can walk and run");
   }
}
public class TestDog {
   public static void main(String args[]) {
      Animal b = new Dog(); // Animal reference but Dog object
      b.move(); // runs the method in Dog class
   }
}

输出

这将产生以下结果 -

Animals can move
Dogs can walk and run