Super Keyword in Java

  • 0
Super keyword is one of the most confusing an exciting features of Java. In this article, I will try to demonstrate the two uses of super keyword. The two uses of super keyword are
  1. to call the constructor of immediate Superclass of subclass. Subclass is the one who has has inherited, and Superclass is the one who has been inherited.
  2. to call and access hidden members of Superclass.
Fallowing program clearly shows the function of super keyword.
package ClassIllustration;

class A
{
 private int a;
 
 A(int a)
 {
  this.a = a;
 }
 
 void display()
 {
  System.out.println("Value of A is " + a);
 }
}

class B extends A
{
 private int b;
 
 B(int a, int b)
 {
  super(a);
  this.b = b;
 }
 
 void display()
 {
  super.display();
  System.out.println("Value of B is " + b);
 }
}
 
 class SuperKeyWordIllustration
 {
 public static void main(String args[])
 {
  B b = new B(5, 10);
  b.display();
 }
}
As you can see, constructor of class A has been called with super(a) statement in line number 24. Because of instance variable hiding, display method of class A is now hidden. Any call to display() method from B's instance will lead to execution of class B's display() method. To call the hidden method of Superclass, we must use super. This has been done in line number 30, where super is used to call the display() method of Superclass. In general, this must have syntax of
super.method_name(argument_list);
To compile the program
javac -d . SuperKeyWordIllustration.java
And to run
java ClassIllustration.SuperKeyWordIllustration
Here is the sample output I gathered,
Value of A is 5

Value of B is 10

Stay Tuned to Java Journal for more explanations.

No comments:

Post a Comment