SUPER KEYWORD JAVA


Super Keyword In JAVA | Core Java Tutorial | Minigranth

Super Keyword In Java : Introduction

  • Super keyword in Java which is used by subclass to refer to immediate parent class.
  • Super keyword is used in many ways out of which two most common ways are demonstrated below along with their syntax and respective examples.
  1. Using super keyword to refer immediate parent class member(field and method).

    • A subclass can refer an immediate parent class member by using Member can be an instance variable or method of parent class.
    • Syntax : To refer to immediate parent class member.

      super.member;


    • Using super in this context is useful when some members in both parent and child class are named same and you want to differentiate them.
    • Let’s see an example demonstrating this use of super.

    • This image describes a program supporting, Using super keyword to refer immediate parent class member(field and method).
      Super Keyword Example : Case 1

      This image describes output of a program supporting, Using super keyword to refer immediate parent class member(field and method).
      Super Keyword Output : Case 1

  2. Using super keyword to invoke immediate parent class constructor.

    • We can invoke immediate parent class constructor by using super().
    • super() is used to invoke default constructor and super(parameters….) is used to invoke parameterized constructor. Let's observe this with an example.

    • This image describes the program supporting, Using super keyword to invoke immediate parent class constructor. Super Keyword Example : Case 2

      This image describes the output of a program supporting, Using super keyword to invoke immediate parent class constructor.
      Super Keyword Output : Case 2

      Note : Invoking constructor using super should be the first statement in the block.