Home  >  Article  >  Java  >  super keyword in Java

super keyword in Java

PHPz
PHPzforward
2023-09-16 22:57:031253browse

super keyword in Java

  • #The super variable refers to the direct parent class instance.
  • Super variables can call direct parent class methods.
  • super() acts as the direct parent class constructor and should be the first line in the child class constructor.

Use the super keyword when calling the superclass version of an overridden method.

Example h2>

Live Demonstration

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
   }
}

Output

This will produce the following results -

Animals can move
Dogs can walk and run

The above is the detailed content of super keyword in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete