OOPS in JAVA 14
super Keyword
The super keyword in java is a reference variable that is 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.
Usage of Java super Keyword
1. super is used to refer immediate parent class instance variable.
2. super() is used to invoke immediate parent class constructor.
3. super is used to invoke immediate parent class method.
1. super is used to refer immediate parent class instance variable
class Vehicle{
int speed=50;
}
class Bike1 extends Vehicle{
int speed=100;
void display(){
System.out.println(super.speed); //will print speed of Vehicle
}
public static void main(String args[]){
Bike1 b=new Bike1();
b.display();
}
}
Output: 50
2. super() is used to invoke parent class constructor.
class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
class Bike2 extends Vehicle{
Bike2(){
super();//will invoke parent class constructor
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike2 b=new Bike2();
}
}
Output:
Vehicle is created
Bike is created
NOTE: super() is added in each class constructor automatically by compiler.
3. super can be used to invoke parent class method
class Person{
void message(){System.out.println("welcome");}
}
class Student16 extends Person{
void message(){System.out.println("welcome to java");}
void display(){
message(); //will invoke current class message() method
super.message();//will invoke parent class message() method
}
public static void main(String args[]){
Student16 s=new Student16();
s.display();
}
}
Output:
welcome to java
welcome
NOTE: super cannot be referenced from a static method.
No comments:
Post a Comment
Hai , Post your comment . (required, Bugs, Errors )