• Home
  • Recent Q&A
  • Java
  • Cloud
  • JavaScript
  • Python
  • SQL
  • PHP
  • HTML
  • C++
  • Data Science
  • DBMS
  • Devops
  • Hadoop
  • Machine Learning
in JAVA by
When can you use super keyword?

1 Answer

0 votes

The super keyword is used to access hidden fields and overridden methods or attributes of the parent class.

Following are the cases when this keyword can be used:

Accessing data members of parent class when the member names of the class and its child subclasses are same.

To call the default and parameterized constructor of the parent class inside the child class.

Accessing the parent class methods when the child classes have overridden them.

The following example demonstrates all 3 cases when a super keyword is used.

public class Parent{

       private int num = 1;



           System.out.println("Parent class default constructor.");



       Parent(String x){

           System.out.println("Parent class parameterised constructor.");



       public void foo(){

           System.out.println("Parent class foo!");




   public class Child extends Parent{

       private int num = 2;



           System.out.println("Child class default Constructor");


           super();    // to call default parent constructor

           super("Call Parent");    // to call parameterised constructor.



       void printNum(){


           System.out.println(super.num); //prints the value of num of parent class




       public void foo(){

           System.out.println("Parent class foo!");

           super.foo();    //Calls foo method of Parent class inside the Overriden foo method of Child class.



Related questions

0 votes
asked Oct 16, 2020 in JAVA by SakshiSharma
0 votes
asked Jan 27, 2020 in JAVA by rahuljain1