Super keyword in Java Example wpaccuracy

please click here for more wordpress cource

In Java, the super keyword is used to refer to the parent class of a subclass. It can be used to access methods, variables, and constructors of the parent class.

Here’s an example:

public class Animal {
    String name;

    public Animal(String name) {
        this.name = name;
    }

    public void makeSound() {
        System.out.println("Animal sound!");
    }
}

public class Dog extends Animal {
    int age;

    public Dog(String name, int age) {
        super(name);
        this.age = age;
    }

    public void makeSound() {
        super.makeSound();
        System.out.println("Woof!");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog("Buddy", 3);
        myDog.makeSound();
    }
}

In this example, we have a Dog class that extends the Animal class. The Animal class has a constructor that takes a name parameter and a makeSound() method that prints “Animal sound!”. The Dog class has an additional age variable and overrides the makeSound() method to print “Woof!”.

In the Dog class constructor, we use the super keyword to call the Animal class constructor and pass the name parameter. In the makeSound() method of the Dog class, we use the super keyword to call the makeSound() method of the parent class, and then add “Woof!” to the output.

In the Main class, we create a Dog object called myDog with the name “Buddy” and age 3. We then call the makeSound() method of the myDog object.

The output will be:

Animal sound!
Woof!

This demonstrates how the super keyword can be used to access the parent class constructor and methods from a subclass.

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *