Following are the uses of super keyword:
- To refer the immediate super class constructor
- To refer the immediate super class members
Refer super class constructor:
The super keyword can be used to invoke the constructor of its immediate super class and pass data to it. Syntax for doing so is given below:
super(parameters-list);
When writing the above statement inside the constructor of the derived class, it must be the first line. It is a mandatory requirement.
For understanding how this works, let’s consider our previous example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | class Student { private String name; private String regdNo; private int age; Student(String name, String regdNo, int age) { this.name = name; this.regdNo = regdNo; this.age = age; } public void getName() { System.out.println("Student’s name is: " + name); } public void getRegdNo() { System.out.println("Student’s registered number is: " + regdNo); } public void getAge() { System.out.println("Student’s name is: " + age); } } class CSEStudent extends Student { static final String branch = "CSE"; CSEStudent(String name, String regdNo, int age) { super(name, regdNo, age); } public void getBranch() { System.out.println("Student’s branch is: " + branch); } } public class Driver { public static void main(String[] args) { CSEStudent s1 = new CSEStudent("Teja", "10AB001", 20); s1.getName(); s1.getRegdNo(); s1.getAge(); s1.getBranch(); } } |
In the above example you can see that the data in Student class is made private. We can still pass data from the derived class CSEStudent to its parent class Student using the super construct given below:
super(name, regdNo, age);
You can also see that the above statement is the only line inside the CSEStudent class constructor. If there were multiple lines, the above line must be the first line.
Refer super class members
Second use of super keyword (in sub class) is to access the hidden members of its immediate super class. To understand this let’s consider the following example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class A { int x; public void display() { System.out.println("This is display in A"); } } class B extends A { int x; public void display() { System.out.println("Value of x in A is: " " + super.x); super.display(); System.out.println("This is display in B"); } } class Driver { public static void main(String[] args) { B obj = new B(); obj.display(); } } |
In the above example we can see that we are using the super keyword in two places. First use is to display the value of variable x of the super class A using the following expression:
super.x
Second use was for calling the display() method of the super class A in the sub class B using the following construct:
super.display()
Take your time to comment on this article.