PREV NEXT
JAVA super keyword is used to refer the members of immediate parent class.
Accessing parent class variable using JAVA super keyword:
In the below example, class B is a subclass of class A. The display() method of class B prints the value of x. Both class A and class B have the variable x.The compiler by default, takes the value of current class instance variable. But when the parent class instance variable is to be accessed, then the super keyword is used.
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 |
class A{ int x = 10; …} class B extends A{ int x = 20; Void display(){ System.out.println(“value of x:”+x); } public static void main(String args[]) { B obj = new B(); obj.display(); } } |
Output:
Value of x:20 |
In the below example the display method of class B prints the value of parent class instance variable x. Here ‘super.x’ refers to the parent class instance variable.
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 |
class A{ int x = 10; …} class B extends A{ int x = 20; Void display(){ System.out.println(“value of x:”+super.x); } public static void main(String args[]) { B obj = new B(); obj.display(); } } |
Output:
Value of x:10 |
Accessing parent class method using super keyword:
In the below example, class B is a subclass of class A. Both class A and class B have the method message().The compiler by default, calls the message() method in the current class. But when the parent class method is to be called, then the super keyword is used. Here ‘super.message()’ calls the message() method of parent class.
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 |
class A{ Void message(){ System.out.println(“Display of A”); } } class B extends A{ Void message(){ System.out.println(“Display of B”); } Void display() {message(); super.message(); } public static void main(String args[]) { B obj = new B(); obj.display(); } } |
Output:
Display of B
Display of A |
Calling parent class constructor using super keyword:
Super() invokes parent class constructor.
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 |
Class A { A() { System.out.println(“A’s constructor”); } } Class B extends A{ B() { super(); System.out.println(“B’s constructor”); } Public static void main(String args[]) { B obj = new B(); } } |
Output:
A’s constructor
B’s constructor |