What is super keyword?
Output:
Salary: 20000
Example program using super keyword:
In the above example Employee and HR both class have a common property salary. Instance variable of current class is refered by instance bydefault, but to refer parent class instance variable, we use super keyword to distinguish between parent class instance variable and current class instance variable.
Output:
Salary: 10000
The super keyword in java is a reference variable that used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e. referred by super reference variable.
Example program without using super keyword:
1 2 3 | class Employee{ float salary = 10000; } |
1 2 3 4 5 6 7 8 9 10 11 12 | class HR extends Employee{ float salary = 20000; void display(){ System.out.println("Salary: " + salary);// print current class salary } public static void main(String[] args){ HR obj = new HR(); obj.display(); } } |
Output:
Salary: 20000
Example program using super keyword:
In the above example Employee and HR both class have a common property salary. Instance variable of current class is refered by instance bydefault, but to refer parent class instance variable, we use super keyword to distinguish between parent class instance variable and current class instance variable.
1 2 3 | class Employee{ float salary = 10000; } |
1 2 3 4 5 6 7 8 9 10 11 12 | class HR extends Employee{ float salary = 20000; void display(){ System.out.println("Salary: " + super.salary);// print base class salary } public static void main(String[] args){ HR obj = new HR(); obj.display(); } } |
Output:
Salary: 10000
No comments:
Post a Comment