What is the super Keyword in Java?
The super keyword refers to the immediate parent class object. It is used to access parent class methods, constructors, and variables when hidden by subclass.
1. Access Parent Class Variable
class Animal {
String color = "White";
}
class Dog extends Animal {
String color = "Black";
void printColor() {
System.out.println(color); // Black (child)
System.out.println(super.color); // White (parent)
}
public static void main(String[] args) {
Dog d = new Dog();
d.printColor();
// Output:
// Black
// White
}
}
2. Invoke Parent Class Method
class Vehicle {
void run() {
System.out.println("Vehicle is running");
}
}
class Bike extends Vehicle {
@Override
void run() {
System.out.println("Bike is running safely");
}
void display() {
run(); // Calls child method
super.run(); // Calls parent method
}
public static void main(String[] args) {
Bike b = new Bike();
b.display();
// Output:
// Bike is running safely
// Vehicle is running
}
}
3. Invoke Parent Class Constructor
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
System.out.println("Person constructor called");
}
}
class Student extends Person {
int studentId;
Student(String name, int age, int id) {
super(name, age); // Must be first statement
this.studentId = id;
System.out.println("Student constructor called");
}
void display() {
System.out.println("Name: " + name + ", Age: " + age + ", ID: " + studentId);
}
public static void main(String[] args) {
Student s = new Student("Alice", 20, 101);
s.display();
}
}
// Output:
// Person constructor called
// Student constructor called
// Name: Alice, Age: 20, ID: 101
Important Rules
- super() must be the first statement in a constructor
- super cannot be used in static contexts
- Unlike this, super does not refer to current object but parent part
this vs super - Quick Comparison
| this | super |
|---|---|
| Refers to current object | Refers to parent object |
| Access current class members | Access parent class members |
| Can call same class constructors | Can call parent class constructors |
Deepen your Java OOP knowledge with Online Learner!
0
likes
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
