ody wellnwill Marathahalli Bangalore

super keyword

super keyword can be used to refer the members (variable, method, and constructor) of immediate super class.

super keyword can be used in the following ways

  • To call the immediate super class variable.
  • To call the immediate super class methods.
  • To call the immediate super class constructor

To call the immediate super class variable

super keyword can be used to refer both instance and static variables of immediate super class from the constructor or non-static methods of sub class.

Syntax: super.

To call the immediate super class methods

super keyword can be used to refer the member functions (methods) of immediate super class from the constructor or non-static methods of sub class.

Syntax: super.;

To call the immediate super class constructor

  • super keyword can be used to call the constructor of super class from the body of sub class

    Syntax: super(number_of_parameter);

  • We can use super() inside constructor only and this statement must be first statement inside the constructor.
  • If we are not writing super() then compiler will always add super() as a first statement.
  • We cannot use super keyword from static context.
  • We cannot access private members of parent class by super keyword.
class Parent
{
 int a=10;
 void display()
 {
  System.out.println("display of Parent");
 }
}
class Child extends Parent
{
 int a=20;
 void display()
 {
  System.out.println("display of child");
  System.out.println(a);
  System.out.println("parent a:"+super.a);
  super.display();
 }
}

class Test
{
 public static void main(String args[])
 {
  Child c1=new Child();
  System.out.println(c1.a);
  c1.display();
 } 
}
Output:
20
display of child
20
parent a:10
display of parent






class Parent
{
 Parent()
 {
  System.out.println("default cons of Parent");
 }
 Parent(int a)
 {
  System.out.println("arg cons of Parent");
 }
 }
class Child extends Parent
{
 Child()
 {
  super(); // call to default constructor of super class
  System.out.println("default cons of Child");
 }
Child(int a)
 {
  super(a);//call to argument constructor of super class
  System.out.println("arg cons of Child");
 }
}
class Test1{
 public static void main(String args[]) {
  Child c1=new Child();
  Child c2=new Child(10); 
 } 
}
Output:default cons of parent
            default cons of child
            arg cons of parent
            argt cons of child



class Parent 
{
 Parent()
 {
  System.out.println("default cons of Parent");
 }
 }
class Child extends Parent
{
}
class Test9
{
 public static void main(String args[])
 {
  Child c1=new Child(); 
 } 
}
output:default cons of Parent

Footer with Map

Top