Super Keyword in java:
The super keyword is used to access the member of the superclass from the subclass. Super can only be used within a derived class constructor method.
The super keyword in Java has two general forms:
- calls the superclass constructor
- To access the member of the superclass that has been hidden by the member of the subclass.
1.Using super to call the superclass constructor:
A subclass can call a constructor method to define by its superclass by using the super keyword.
super(argument.list);
where,
argument.list: specifies any parameter need by the constructor in the superclass.
note: The argument list in the super call must match the order and the type of the inheritance variables declared in the superclass.
Example:
class supdemo
{
int a;
supdemo(int x)
{
a=x;
}
void dispaly_supdemo()
{
System.out.println("a="+a);
}
}
class supdemo1 extends supdemo
{
int b;
supdemo1(int x,int y)
{
super(x);
b=y;
}
void display_subdemo1()
{
System.out.println("b="+b);
}
}
class finalsuper
{
public static void main(String args[])
{
supdemo1 s1=new supdemo1(4,8)
s1.display_supdemo();
s1.display_supdemo1();
}
}
The output of this program is:
a=4
b=8
2. Accessing the member of a superclass that has been hidden by a member of subclass:
A class can access a hidden member variable through it, superclass. The general form is:
super.memeber
here,
a member can be either a " method or an instance variable".
super.varname;
super.methodname(parameter_list);
here,
varname: is the name of the variable in the superclass.
method name: is the name of the overridden method. Access the superclass variable and constructor a subclass by using the same variable name.
Example:
class supervar
{
int x=10;
}
class supervar1 extends supervar
{
int x=20;
void display()
{
System.out.println("The value of x="+x);
System.out.println("The value of super x="+super.x);
}
}
class supervariable
{
public static void main(String args[])
{
supervar1 spv=new supervar1();
spv.display();
}
}
The output of this program is:
The value of x=20
The value of super x=10
Usage of super keyword:
- Super is used to refer to immediate parent class instance variable.
- Super() is used to invoke method parent class constructor.
- super is used to invoked immediate parent class method.
Guys, I hope you understand super keyword in java. please write comments if you guys find any incorrect or else if you guys want to share more info about the super keyword in Java.
No comments:
Post a Comment