Scientech Easy Super Keyword in Java | Uses & Example Programs | Scientech Easy

Monday, January 28, 2019

Super Keyword in Java | Uses & Example Programs

In this tutorial, we will learn a very important and easy topic Super keyword in Java. It can be used for calling immediate superclass's instance variable, constructor, and method. Basically, The keyword super comes into the picture with the concept of inheritance in Java. So, before going to learn super keyword, you must have familiar with Inheritance in Java so that you don't have any problem to understand the example programs.

Super Keyword in Java

The super keyword in Java is a reference variable that refers an immediate superclass object. In other words, It refers to the superclass of the current object. It allows the users to access the members of a superclass in a subclass. Super keyword always represents superclass object. It can be applied to variable, method, and constructor. 

Why do need/use Super keyword in Java?

Let's take one simple example program to understand the need of super keyword in Java. Suppose, we have a superclass as Person and Employee as a subclass as below.
    package com.superKeyword; public class Person { int age=50; } package com.superKeyword; public class Employee extends Person{ int age=30; void insertStudentAge(){ int age=20; // Here, we have two ways to call instance variable 'age' of the person. // 1st way: Person p=new Person(); System.out.println(p.age); // 50 // 2nd way: System.out.println(super.age); // 50 // calling Local variable. System.out.println(age); // Calling instance variable of the same class. System.out.println(this.age); // 30 } }
From the above program, if you see that In the Employee class' insertStudentAge() method, there are two ways to call age variable of person class.
1st way: In a 1st way, we have created an object of person class and have called age variable of person class using reference variable p. But, this is not a good affordable option. Why? This is because for sake of one variable here we are loading the complete class person which wastes memory unnecessarily. In other words, unnecessary memory will get allocated to other members for just calling variable 'age'.
2nd way: In a 2nd way, we have just called the age directly by using a super keyword which will not waste of memory. By this way, we have achieved our objectives as well as calling a single variable age of the person.
Note: We can say that just to bypass the same class variables and methods while calling we use the super keyword. It's all about memory management.

Use of super keyword in Java

Java super keyword can be used in three ways:
1. To refer immediate parent class instance variable.
2. To call immediate parent class constructor.
3. To invoke immediate superclass method.
To call the superclass instance variable or method, we have two options. See the below figure.
Java super keyword, Java super constructor, Java super method.

Calling Superclass Instance variable

The keyword "super" can be used to call an instance variable of the superclass. When you declare an instance variable in the subclass with the same name as provided in the superclass, you cannot access the instance variable of the superclass by its name in the subclass. This is because it has the same name. To solve this problem, we use super keyword in the subclass to refer to the superclass members from the subclass. The syntax to call superclass instance variable is like this:
For example:
     super.a;  //  a is an instance variable.
Let's see a simple example program to clarify the concepts.
Program source code 1:
    package com.superKeyword; public class SuperDemo { // Declare an instance variable and initialize the value of the variable. int x=100; } package com.superKeyword; public class Sub extends SuperDemo { // Declare an instance variable with the same name as provided the name of an instance variable in the superclass. int x=200; void display(){ // Call the superclass variable x. But, it will call the variable of class Sub due to the same name. System.out.println("Value of variable of the class Sub: " +x); // Since we have created an object of class Sub. Therefore, it will print the value of the variable of the class Sub. // To call superclass instance variable, Here, we will use the super keyword as a reference variable. System.out.println("Value of variable of the SuperDemo: " +super.x); // x of class SuperDemo is called. } public static void main(String[] args) { Sub s=new Sub(); s.display(); } }
    Output: Value of variable of the class Sub: 200 Value of variable of the SuperDemo: 100
In this example program, the super keyword is used to access the members of SuperDemo parent class that is hidden in the Sub child class.

Calling Superclass Constructors

The keyword "super" is used to invoke the superclass's constructor from within a subclass's constructor. If you don't use super keyword to call the superclass constructor in any class's constructor, JVM will put the super at first line in the class's constructor to call the constructor of the superclass.
For example 1:
    public class A { 
         public A() {   // Default constructor put by JVM at Run time..
           // invisible super(); present here.
For example 2:
   public class X  {
       public X( ) {
         System.out.println("Hello Java");
    super( ); // Error because super must be at first line of constructor.
   void msg( ) {
       super( );  // Error as this is method where we tried to add super();
     X(int a) {
        super( );  // No error.
        super(10);  /// Error.
   } }
The syntax to call a superclass constructor is:
   super(), or super(arguments);

Points to remember:
1. The statement super() calls the no-argument constructor of its superclass.
2. The statement super(arguments) calls the parent class constructor that matches the arguments.
3. The statement super() or super(arguments) must be the first line of the child class constructor. Calling a parent class constructor's name in the child class causes the syntax error. 
4. A constructor is used to create an object or instance of the class. Unlike the properties and methods, the constructors of the parent class are not inherited in a child class. They can only be called from the constructor of child class using the keyword super. The parent class constructors are executed while creating the object of the child class.
5. A parent class's constructor is called before the child class's constructor. This is called constructor chaining.
6. If a class is declared to be extended, it is better to use a no-arg constructor to make the class easy to extend and to avoid the programming errors. Consider the following program source code.
    package com.superKeyword; public class Fruit { // Here, Fruit does not have defined a no-arg constructor. //Fruit has an explicit constructor defined public Fruit(int x) { System.out.println("Explicit fruit constructor defined"); } } package com.superKeyword; public class Apple extends Fruit { public static void main(String[] args) { Apple a=new Apple(); } }
In the above source code, there is no explicitly defined constructor in class Apple. But, a default no-arg constructor is declared implicitly in the class Apple. Since Apple is the subclass of Fruit class. Therefore, it will automatically call the fruit's no-arg constructor. However, Fruit does not have a no-argument constructor because fruit has defined an explicit constructor. Therefore, the program cannot be compiled. 

To compile the above source code, declare a no-arg constructor in the class Fruit. Let's see the program source code.
Program source code 2:
    package com.superKeyword; public class Fruit { // Here, Fruit does not have defined a no-arg constructor. To compile the program, declare a no-arg constructor. Fruit(){ System.out.println("Fruit no-arg constructor"); } //Fruit has an explicit constructor defined public Fruit(int x){ System.out.println("Fruit constructor"); } } package com.superKeyword; public class Apple extends Fruit { public static void main(String[] args) { Apple a=new Apple(); } }
    Output: Fruit no-arg constructor
7. There is not any super.super in Java. It is illegal.
8. Recursion by using the super call to a constructor is a compile-time error in java. See compile time error in the below example code:
For example:
    package com.scientecheasy.Super;
    public class B extends B {
       // super( );  // Recursion occurs due to go on calling the same class.
Note: In this example, recursion between superclass to the constructor will be there because we are extending the same class itself. Consider invisible super().

See the below example source code how super keyword navigates the flow of our program.
Program source code 3:
    package com.superKeyword; public class P { // super(); // By default super is here. P(){ System.out.println("P class's no-arg constructor"); } P(int x) { System.out.println("P class's one argument constructor"); } public void show(){ System.out.println("P class's method"); } } package com.superKeyword; public class Q extends P { Q() { // super(); // JVM put the keyword 'super' by default at runtime. } public void show(){ System.out.println("Q class's method"); } } package com.superKeyword; public class R extends P { R(){ // super(); // JVM put super() by default at runtime. System.out.println("R class's no-arg constructor"); } } package com.superKeyword; public class Client { public static void main(String[] args) { // Create an object of class R and call the method show() using reference variable obj. R obj=new R();; } }
    Output: P class's no-arg constructor R class's no-arg constructor P class's method

 Calling Superclass Methods

The keyword "super" can also be used to reference a method in addition to the constructor in the superclass. If a method of the subclass overrides one of the methods of its superclass, the overridden method can be called through the use of a 'super' keyword. The syntax is like this:
   super.method_name() or super.method_name(parameters);
For example:
See below a simple example program.
Program source code 4:
    package com.superKeyword; public class Student { // Overridden method. void displayInfo(){ System.out.println("I am John"); } } package com.superKeyword; public class School extends Student { // Overriding method. void displayInfo(){ System.out.println("My school's name is RSVM"); } void msg(){ super.displayInfo(); // displayInfo of class Student is called. displayInfo(); // displayInfo of class School is called. } public static void main(String[] args){ School sc=new School(); sc.msg(); } }
    Output: I am John My school's name is RSVM
In this program, the parent class 'Student' and child class 'School' both have displayInfo() method. Since the method of the child class overrides the method 'displayInfo' of its parent class. If you call the displayInfo() method by using reference variable sc, it will call the displayInfo() method of the child class, not of the parent class. This is because an object is created for the child class and the object reference variable 'sc' is pointing to the object of the child class.
In this case, we can use super.displayInfo() to invoke the method displayInfo() defined in the parent class. 
Note: Now, suppose class X extends class Y, Y extends class Z, and a method msg() is defined in class Z. Can you invoke super.super.msg() from class X? The answer is no. It is illegal to have such a chain of supers in java. 

Final words 
Hope that this article has covered all the important topics related to the super keyword in Java. In this chapter, we have discussed the calling superclass's instance variable, constructors, and methods with simple practical example programs that are very important for freshers.
Thanks for reading!