What is super keyword in Java?
super is a reference variable used inside a subclass (child class) to access members (methods, variables, constructors) of the parent class (superclass).
When is super used?
Use Case----> Purpose Example
Access parent class variable---> super.name refers to the superclass name
Call parent class method---> super.display() calls superclass method
Call parent constructor---> super(...) calls superclass constructor
Example:
Imagine you are building an Employee Payroll System for a company. There are:
Base class Employee → common features like name, salary
Child class Manager → adds extra features like bonus
We’ll use super to:
Access base class constructor from Manager
Access methods and variables of the parent class
Java Program Using super Keyword
// Parent class
class Employee {
String name;
double salary;
// Constructor
Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
void displayDetails() {
System.out.println("Employee Name: " + name);
System.out.println("Base Salary: ₹" + salary);
}
}
// Child class
class Manager extends Employee {
double bonus;
// Constructor with super() call
Manager(String name, double salary, double bonus) {
super(name, salary); // Call parent class constructor
this.bonus = bonus;
}
void displayDetails() {
super.displayDetails(); // Call parent method
System.out.println("Bonus: ₹" + bonus);
System.out.println("Total Salary: ₹" + (salary + bonus));
}
}
public class CompanyPayroll {
public static void main(String[] args) {
Manager m1 = new Manager("Priya", 50000, 10000);
m1.displayDetails();
}
}
Creates a Manager object m1 with:
name = "Priya"
salary = ₹50,000
bonus = ₹10,000
Calls m1.displayDetails() → prints all info.
Output:
Employee Name: Priya
Base Salary: ₹50000.0
Bonus: ₹10000.0
Total Salary: ₹60000.0
No comments:
Post a Comment