Website For Developers

super keyword in Java



super keyword in Java example

class Parent {
   String str = "I like Apples.";
}

class Child extends Parent {
   String str = "I like Mangoes.";
   void show() {
     System.out.println(str); // this statement print child class string.
     System.out.println(super.str); //with super, this statement print parent class string.
   }

   public static void main (String [] args) {
     Child object = new Child();
     object.show();
   }
}

Output

I like Mangoes.
I like Apples.


Compiler automatically added super() in each class constructor.

Example: super() for parent constructor

class Parent {
   // parent constructor.
   Parent() {
     System.out.println( "This is Parent class Constructor." );
   }
}

class Child extends Parent {
   // child class constructor.
   private Child() {
     super(); // invoke parent constructor.
     System.out.println( "This is Child class Constructor." );
   }
   public static void main (String [] args) {
     Child object = new Child();
   }
}

Output

This is Parent class Constructor.
This is Child class Constructor.


Test yourself

Take the above example and remove super(); from child class constructor. What will be the output of the program?