Super Keyword in Java | Learn in 2 mins
The super
keyword is Java, refers to the immediate parent class of the current class. It is used to access variables, methods, and constructors of the parent class.
Here are some examples of how the super
keyword can be used in Java:
- Accessing variables of the parent class:
class Child extends Parent { int x = 10; int y = 20; void display() { System.out.println(x); System.out.println(y); System.out.println(super.x); System.out.println(super.y); } }
In this example, the Child
class has two variables x
and y
, which are shadowing the variables of the same name in the Parent
class. To access the variables of the Parent
class, you can use the super
keyword.
- Accessing methods of the parent class:
class Child extends Parent { void display() { super.display(); } }
In this example, the Child
class has a method called display()
that calls the display()
method of the Parent
class using the super
keyword.
- Calling the parent class constructor:
class Child extends Parent { Child() { super(); } }
In this example, the Child
class has a constructor that calls the constructor of the Parent
class using the super
keyword.
It is important to note that the super
keyword must be used before the parent class’ variables, methods, and constructors are accessed or called.
Leave a Reply