What is super keyword ?
The super keyword in Java is used to refer to the immediate parent class object. It is commonly used to:
1. Access Parent Class Methods: To call methods from the parent class that have been overridden in the subclass.
2. Access Parent Class Constructors: To invoke a constructor of the parent class from the subclass constructor.
3. Access Parent Class Fields: To access fields of the parent class if they are hidden by subclass fields.
Key Uses of super #
1. Calling Parent Class Methods: If a method is overridden in the subclass, super can be used to call the parent class’s version of that method.
2. Calling Parent Class Constructor: super can be used in the subclass constructor to explicitly call a constructor of the parent class.
3. Accessing Parent Class Fields: super is used to refer to fields in the parent class that are hidden by fields in the subclass.
Examples #
1. Calling Parent Class Methods
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks");
}
void callSuperSound() {
// Calling the parent class method
super.makeSound();
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.makeSound();
myDog.callSuperSound();
}
}
Output:
Dog barks
Animal makes a sound
In this example, super.makeSound() is used in the Dog class to call the makeSound method from the Animal class, which has been overridden in Dog.
2. Calling Parent Class Constructor
class Animal {
Animal() {
System.out.println("Animal constructor");
}
}
class Dog extends Animal {
Dog() {
// Calling the parent class constructor
super();
System.out.println("Dog constructor");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
}
}
In this example, super() in the Dog constructor calls the Animal constructor before executing the Dog constructor’s own code.
3. Accessing Parent Class Fields
class Animal {
String color = "Unknown";
}
class Dog extends Animal {
String color = "Brown";
void printColors() {
// Accessing parent class field
System.out.println("Parent color: " + super.color);
// Accessing subclass field
System.out.println("Current color: " + this.color);
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.printColors();
}
}
In this example, super.color is used to access the color field from the Animal class, while this.color accesses the color field from the Dog class.
Summary #
- super Keyword: Refers to the parent class’s fields, methods, and constructors.
- Calling Parent Class Methods: super.methodName()
- Calling Parent Class Constructor: super()
- Accessing Parent Class Fields: super.fieldName
The super keyword helps in clarifying which parent class method, field, or constructor you are referring to, particularly in cases where the subclass overrides or hides members of the parent class.