1 Aug 2012

super keyword in java with example


the super keyword indicates the following :

1. The super keyword in java programming language refers to the superclass of the class where the super keyword is currently being used.
2. The super keyword as a standalone statement is used to call the constructor of the super class of the class which extends 
the super class or to call the method of the super class of the class which extends the super class .

Example to use the super keyword to call the constructor of the superclass in the base class:
public class class1
{
public class1(String arg)
{
super(arg);
}
..................
}
-->  The syntax super.<method_Name>() is used to give a call to a method of the superclass in the base class.
--> This kind of use of the super keyword is only necessary when we need to call a method that is overridden in this base class in order to specify that the method should be called on the superclass.


Example to use the super keyword with a variable:

class A
{
int k = 10;
}
class Test extends A
{
public void m()
{
System.out.println(super.k);
}
}

Example to use the super keyword with a method:


public class class1
{
.............................//block of statements
public String fun()
{
 ............................//block of statements
}
.............................//block of statements
}


public class class2 extends class1
{
.............................//block of statements
public String fun()
{
return super.fun();
}
.............................//block of statements
}


0 comments:

Post a Comment