Curriculum
In Java, the super
keyword is used to refer to the superclass of a subclass. It is used to call the superclass constructor or access the superclass’s properties or methods from within a subclass.
Here is an example that illustrates the use of the super
keyword in Java:
class Animal { String name; public Animal(String name) { this.name = name; } public void eat() { System.out.println(name + " is eating"); } } class Dog extends Animal { String breed; public Dog(String name, String breed) { super(name); this.breed = breed; } public void bark() { System.out.println(name + " is barking"); } public void eat() { super.eat(); // Calls the eat() method in the superclass System.out.println(name + " the " + breed + " is eating"); } } public class Main { public static void main(String[] args) { Dog dog = new Dog("Buddy", "Labrador"); dog.bark(); dog.eat(); } }
In this example, we have a superclass Animal
with a constructor that takes a name
parameter and a method eat()
that prints a message indicating that the animal is eating. We then have a subclass Dog
that extends Animal
, and has a constructor that takes a name
and a breed
parameter, and a method bark()
that prints a message indicating that the dog is barking.
In the main()
method, we create a Dog
object with the name “Buddy” and the breed “Labrador”. We then call its bark()
and eat()
methods. When the eat()
method is called, it first calls the eat()
method in the superclass using the super.eat()
syntax, and then prints a message indicating that the dog is eating.
The super
keyword is used in the Dog
class’s constructor to call the Animal
class’s constructor with the name
parameter. This initializes the name
property in the Animal
class, which can then be accessed in the Dog
class. In the eat()
method, the super
keyword is used to call the eat()
method in the Animal
class, and then the name
and breed
properties are printed to the console.