Super Keyword in Java

Super Keyword in Java

Super Keyword in Java

Super Keyword in Java:

In Java, super is a keyword that refers to the immediate parent class of a class. It is used to access the variables and methods of the parent class, and to invoke the constructor of the parent class.

Here are some of the uses of the super keyword in Java:

  1. Accessing variables and methods of the parent class: When a subclass inherits from a parent class, it can use the super keyword to access the variables and methods of the parent class. For example:
				
					class Animal {
    protected String name;

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

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

class Dog extends Animal {
    public Dog(String name) {
        super(name);
    }

    public void makeSound() {
super.makeSound(); // calls the makeSound method of the parent class
System.out.println("Dog barks");
    }

    public void printName() {
System.out.println("Name: " + super.name); // accesses the name variable of the parent class
    }
}

				
			

In this example, the Dog class inherits from the Animal class and overrides its makeSound method. The Dog class uses the super keyword to call the makeSound method of the parent class before adding its own behavior. It also uses the super keyword to access the name variable of the parent class.

  1. Invoking the constructor of the parent class: When a subclass is instantiated, its constructor must call the constructor of the parent class. This is done using the super For example:
				
					class Animal {
    protected String name;

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

class Dog extends Animal {
    private int age;

    public Dog(String name, int age) {
        super(name); // calls the constructor of the parent class
this.age = age;
    }
}

				
			

In this example, the Dog class has a constructor that takes both a name and an age parameter. The Dog class uses the super keyword to call the constructor of the parent class with the name parameter, and then initializes its own age variable.

In summary, the super keyword is an important tool for accessing the variables and methods of the parent class, and for invoking the constructor of the parent class. It helps to facilitate code reuse and inheritance in Java.

Join To Get Our Newsletter
Spread the love