In Java, the super keyword is used to refer to the superclass (parent class) of the current object. It serves several purposes:
-
Accessing Superclass Methods: You can use
superto call methods from the superclass that have been overridden in the subclass. This allows you to invoke the original method implementation.class Animal { void eat() { System.out.println("Animal eats"); } } class Dog extends Animal { void eat() { super.eat(); // Calls the eat method of Animal System.out.println("Dog eats"); } } public class Main { public static void main(String[] args) { Dog dog = new Dog(); dog.eat(); // Output: Animal eats // Dog eats } } -
Accessing Superclass Constructors: You can use
super()to call a constructor of the superclass. This is often done to initialize inherited fields.class Animal { Animal() { System.out.println("Animal constructor"); } } class Dog extends Animal { Dog() { super(); // Calls the constructor of Animal System.out.println("Dog constructor"); } } public class Main { public static void main(String[] args) { Dog dog = new Dog(); // Output: Animal constructor // Dog constructor } } -
Accessing Superclass Fields: If a subclass has a field with the same name as a field in its superclass, you can use
superto refer to the superclass field.class Animal { String name = "Animal"; } class Dog extends Animal { String name = "Dog"; void printNames() { System.out.println(name); // Prints "Dog" System.out.println(super.name); // Prints "Animal" } } public class Main { public static void main(String[] args) { Dog dog = new Dog(); dog.printNames(); } }
In summary, the super keyword in Java is a powerful tool for accessing superclass methods, constructors, and fields, allowing for better code reuse and organization in object-oriented programming.
