Java Super Keyword
Syntax
super();
super.methodName();
super(instance variable);
Example
class Animal {
String species;
}
class Dog extends Animal {
String breed;
public Dog(String species, String breed) {
super.species = species;
this.breed = breed;
}
public void display() {
System.out.println("This dog is a " + super.species + " and it's bred for " + breed);
}
}
class Main {
public static void main(String[] args) {
Dog dog = new Dog("Canine", "Hunting");
dog.display();
}
}
Output
This dog is a Canine and it's bred for Hunting
Explanation
In Java, the super
keyword is used to refer to the parent class or the super class. It provides a way to call the parent class constructor, methods, and instance variables from the subclass.
When using super
, you can call the parent class constructor using super()
and invoke the parent class method using super.methodName()
. You can also access the parent class instance variable using super.instanceVariable
.
In the example above, we have a Dog
class that extends the Animal
class. When we create an instance of the Dog
class using new Dog("Canine", "Hunting")
, the parent Animal
class constructor is called using super.species = species;
. Then, we call the display()
method in the Dog
class which uses the super.species
instance variable to display the species of the dog along with the breed.
Use
The super
keyword is used to refer to the parent class or the super class in Java. It provides a way to access the parent class constructor, methods, and instance variables from the subclass.
Some use cases of the super
keyword include:
- Accessing parent class methods that have been overridden in the subclass
- Calling the parent class constructor when creating an object of the subclass
- Accessing parent class instance variables from the subclass
Important Points
- The
super
keyword is used to refer to the parent class or the super class in Java. - It provides a way to access the parent class constructor, methods, and instance variables from the subclass.
- You can call the parent class constructor using
super()
and invoke the parent class methods usingsuper.methodName()
. - You can access the parent class instance variable using
super.instanceVariable
. super
keyword is only used in the context of inheritance.
Summary
The super
keyword is a powerful feature in Java that allows you to access the parent class constructor, methods, and instance variables from the subclass. It provides a way to call the parent class constructor, methods, and instance variables without duplicating the code in the subclass. It is especially useful when working with inheritance in Java.