Super Keyword

Super Keyword 

The super keyword in Java is used in subclasses to access superclass members (attributes, constructors and methods).

Uses of super keyword

  1. To call methods of the superclass that is overridden in the subclass.
  2. To access attributes (fields) of the superclass if both superclass and subclass have attributes with the same name.
  3. To explicitly call superclass no-arg (default) or parameterized constructor from the subclass constructor.

 package com.ritesh;
class base{
base(){ //constructor
System.out.println("I am a base constructor");
}
base(int a){ //overloading a base class constructor
System.out.println("I return the value for base constructor of a to be "+ a);
}

static class extra extends base{
extra(){
System.out.println("I am a extra class constructor");
}
}

}

public class super1 {
public static void main(String[] args) {
base.extra p1=new base.extra();

}
}
When I run this program The output will be:
I am a base constructor
I am a extra class constructor

It will automatically call the base class method which has no argument. So to call the base class method which return an argument from the extra class.

we use super keyword on the inheritance.

Program done using super keyword.

package com.ritesh;
class base{
base(){ //constructor
System.out.println("I am a base constructor");
}
base(int a){ //overloading a base class constructor
System.out.println("I return the value for base constructor of a to be "+ a);
}

static class extra extends base{
extra(){
super(2);
System.out.println("I am a extra class constructor");
}
}

}

public class super1 {
public static void main(String[] args) {
base.extra p1=new base.extra();

}
}
And the output will be:
I return the value for base constructor of a to be 2
I am a extra class constructor
Some advance program

package com.ritesh;
class base{
base(){ //constructor
System.out.println("I am a base constructor");
}
base(int a){ //overloading a base class constructor
System.out.println("I return the value for base constructor of a to be "+ a);
}
base(int a, int b){

System.out.println("I return the value for the base class of a and b to be "+a +" and "+ b);
}
base(int a,int b,int c){
System.out.println("I return the value for the base class of a, b and c to be "+a +" and "+ b+" and "+ c);
}

static class extra extends base{
extra(){
super(20,20,40);

System.out.println("I am a extra class constructor");
}
extra(int x){
super(10,20);

System.out.println("I return the value from extra class of x to be"+x);
}
}

}

public class super1 {
public static void main(String[] args) {
base.extra p1=new base.extra(10); //by giving the value 10 we are calling the function of extra method
//which take some parameter


}
}
And the output will be
I return the value for the base class of a and b to be 10 and 20
I return the value from extra class of x to be10

Comments