About Lesson
The super
keyword in Java is a reference variable used to refer to the immediate parent class object. It can be used to access methods and variables from the parent class, as well as to invoke the parent class constructor.
Uses
- Access Parent Class Variables : When a derived class has a field with the same name as a field in its parent class, the
super
keyword can be used to differentiate between the fields of the parent and the child class.
class Animal {
String name = "Animal";
}
class Dog extends Animal {
String name = "Dog";
void printName() {
System.out.println("Name in Dog: " + name);
System.out.println("Name in Animal: " + super.name);
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.printName();
}
}
- Invoke Parent Class Method : The
super
keyword can also be used to call methods of the parent class. This is particularly useful when you want to extend the functionality of the parent class method in the child class.
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
super.sound(); // Calling parent class method
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound();
}
}
- Invoke Parent Class Constructors: The
super
keyword can be used to call the constructor of the parent class. This is typically done to initialize fields of the parent class when an object of the child class is created.
class Animal {
Animal() {
System.out.println("Animal is created");
}
}
class Dog extends Animal {
Dog() {
super(); // Calling parent class constructor
System.out.println("Dog is created");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
}
}