The Keyword "super"
The Keyword "super"
Consider we are extending a class from another class using inheritance , we always create an object to a sub class..this is because we can access all super class and sub class members using sub class object.If super class and sub class members have same name by default only sub class members are accessible.. In this case we can use Super Keyword to access super class member.
Example1:
Example1:
Class Mysuper
{
int i=10;
void show()
{
System.out.println("super class variable:i="+i);
}
}
Class Mysub extends Mysuper
{
int i=20;
void show()
{
System.out.println("sub class variable:i="+i);
}
}
Class TestSuper
{
public static void main(String args[])
Mysub m=new Mysub();
m.show();
}
This will give the following output:
sub class variable:i=20
So if i want to access the variable i in super class we can use the Super keyword.
1.super.variable-To access the variable in super class
2.super.method()-To access the method in super class
3.super(variable)-To access super class parameterised constructor
default constructor of the super class is availabe by default in sub class..so no need to call it .
Example2:
{
int i=10;
void show()
{
System.out.println("super class method="+i);
}
}
Class Mysub extends Mysuper
{
int i=20;
void show()
{
super.show();
System.out.println("sub class method="+i);
System.out.pritln("super class variable="+super.i);
}
}
Class TestSuper
{
public static void main(String args[])
Mysub m=new Mysub();
m.show();
}
Output of this program will be
super class method=10
sup class method =20
super class variable=10
Precise and clear
ReplyDelete