What is the purpose of the super() keyword in Java?
Question
What is the purpose of the super() keyword in Java?
Solution
The super() keyword is used in object-oriented programming to refer to the immediate parent class of the current object. Here are the steps to understand its purpose:
-
Access Parent Class Constructor: The primary use of
super()is to call the constructor of the parent class. This is particularly useful when the parent class has a parameterized constructor, and you need to initialize the parent class's fields from the child class. -
Invoke Parent Class Methods:
supercan also be used to call methods defined in the parent class that have been overridden in the child class. This allows the child class to use the parent class's implementation of a method. -
Access Parent Class Fields: If a field is hidden by a field of the same name in the child class,
supercan be used to access the hidden field in the parent class.
Here is an example to illustrate these points:
class Parent {
int x;
Parent(int x) {
this.x = x;
}
void display() {
System.out.println("Parent x: " + x);
}
}
class Child extends Parent {
int x;
Child(int x1, int x2) {
super(x1); // Calls the constructor of Parent class
this.x = x2;
}
void display() {
super.display(); // Calls the display method of Parent class
System.out.println("Child x: " + x);
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child(10, 20);
child.display();
}
}
In this example:
super(x1)calls the constructor of theParentclass.super.display()calls thedisplaymethod of theParentclass.super.x(if used) would access thexfield of theParentclass.
Similar Questions
What are the uses of super keyword?
What is the purpose of the super() function in Python?
Super keyword in java is used toSelect one:Refer immediate parent class instance variables.Invoke immediate parent class methods.Invoke immediate parent class constructor.All
What is the purpose of the "super()" function in Python?a.It is used to call the constructor of the parent classb.It is used to create a new instance of a classc.It is used to access private attributes of the classd.It is used to define a subclass
The use of "super" keyword is for Calling multiple constructor in same class Calling multiple methods Calling base class constructor in derived class Creating object of the class
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.