Super Keyword in Java
This Java Tutorial article covers one of the most important concepts in Inheritance which is Super Keyword in Java. Here, we’ll go through the uses of super keyword along with examples.
The super keyword in Java is a reference variable a subclass uses to access the object of its immediate parent class. It allows the subclass to access the parent class’s data members (variables, methods, and constructors). The super keyword is used to access the parent class object and is based on the concept of inheritance in Java. It is important to note that the super keyword can only be used inside a subclass and not in a top-level class or interface.
Contents
Best-suited Java courses for you
Learn Java with these high-rated online courses
Why do we need a Super keyword in Java?
There are several reasons why we might need to use the super keyword in Java:
- Access the members of the superclass from within the subclass:
- Invoke the superclass constructor from within the subclass constructor.
- Resolve ambiguity between a field or method in the subclass and a field or method in the superclass.
- Access the static members of the superclass from within the subclass.
Example of Super Keyword in Java
// Superclass definitionclass Animal { // Field to store the animal's name protected String name;
// Constructor to initialize the animal's name public Animal(String animalName) { name = animalName; }
// Method to display the animal's name public void displayName() { System.out.println("Animal's name: " + name); }}
// Subclass definition that extends the Animal superclassclass Cat extends Animal { // Field to store the cat's breed private String breed;
// Constructor to initialize the cat's name and breed public Cat(String animalName, String catBreed) { // Call the superclass (Animal) constructor super(animalName); // Initialize the cat's breed breed = catBreed; }
// Method to display the cat's name and breed public void displayInfo() { // Display the cat's name using the super keyword super.displayName(); // Display the cat's breed System.out.println("Cat's breed: " + breed); }}
class Main { public static void main(String[] args) { // Create an object of the Cat class Cat c = new Cat("Fluffy", "Siamese"); // Display the cat's name and breed c.displayInfo(); }}
In this example, the Cat subclass extends the Animal superclass and overrides the displayInfo method to display the cat’s name and breed. The displayInfo method calls the displayName method of the Animal superclass using the super keyword and then displays the cat’s breed. When the displayInfo method is called on the c object of the Cat class, it displays the following output:
Output:
Animal's name: FluffyCat's breed: Siamese
Uses of Super Keyword in Java
Following are the uses of Super Keyword in Java:
- Access Superclass Data Members (Variables)
- Using Superclass Member Functions (Methods)
- Calls Superclass Constructor
Access Superclass Data Members (or Variables)
Using a super keyword with the same name as data members (variables) in the superclass and subclass can help you access the superclass variables without getting shadowed by its subclass.
Let’s see an example demonstrating the use of the super keyword in Java to access superclass’ same-name data members (variables).
Example:
// SuperClass definitionclass SuperClass { // Declare a variable int variableA;
// Constructor to initialize the variable SuperClass() { variableA = 5; }}
// SubClass definition that extends the SuperClassclass SubClass extends SuperClass { // Declare a variable int variableB;
// Constructor to initialize the variable SubClass() { // A call to superclass variable variableA variableB = super.variableA * 2; }
// Method to display the values of the variables void displayVariables() { System.out.println("The value of variable variableA in superclass SuperClass: " + super.variableA); System.out.println("The value of variable variableB in subclass SubClass: " + variableB); }}
// Main classclass Main { public static void main(String[] args) { // Create an object of the SubClass SubClass obj = new SubClass(); // Call the displayVariables method obj.displayVariables(); }}
Explanation:
In this code, the SuperClass defines a variable variableA and a constructor that initializes the variable to 5. The SubClass extends the SuperClass and defines a variable variableB and a constructor that initializes the variable to twice the value of variableA in the SuperClass. The SubClass also defines a method displayVariables that displays the values of variableA and variableB.
In the main method of the Main class, an object of the SubClass is created, and the display variables method is called to display the values of variableA and variableB. The output shows the values of the variables in the SuperClass and SubClass.
Output:
<strong>The value of variable variableA in superclass SuperClass: 5The value of variable variableB in subclass SubClass: 10</strong>
Using Superclass Member Functions (or Methods)
The subclass can use the super keyword to access is used to access methods (same name) from its superclass.
The below examples demonstrate the use of the super keyword. Here the method display is defined in both parent and subclass. Notice how super keywords help in accessing the member functions (or methods) of the superclass (Quadrilateral) from subclass (Rectangle).
Example:
// Superclass definitionclass QuadrilateralShape { // Method to display the shape type public void displayShapeType() { System.out.println("I am a Quadrilateral"); }}
// Subclass definition that extends the Superclassclass RectangularShape extends QuadrilateralShape { // Method to display the shape type public void displayRectangleType() { System.out.println("I am a Rectangle"); }
// Method to display the shape types public void displayShapeTypes() { // This calls the subclass method (overriding method) displayRectangleType();
// This calls the superclass method (overridden method) super.displayShapeType(); }}
class Main { public static void main(String[] args) { // Create an object of the RectangularShape class RectangularShape r = new RectangularShape(); // Call the displayShapeTypes method r.displayShapeTypes(); }}
Explanation:
The above code defines a superclass QuadrilateralShape with a method displayShapeType that displays the type of shape. It also defines a subclass RectangularShape that extends the QuadrilateralShape class and overrides the displayShapeType method with a new implementation that displays the type of rectangle.
The RectangularShape class also defines a method displayShapeTypes that calls the displayRectangleType method, which is the overriding method in the subclass, and the displayShapeType method, which is the overridden method in the superclass.
In the main method of the Main class, an object of the RectangularShape class is created, and the displayShapeTypes method is called to display the type of rectangle and the type of quadrilateral. The output shows the type of rectangle and the type of quadrilateral.
Output:
I am a RectangleI am a Quadrilateral
Also, Read: Java Operators Explained
Calls Superclass Constructor
As we know by the concept of Constructors in Java, a default constructor is automatically called whenever the respective object of the class is created. However, calling a superclass constructor from the subclass seems impossible regarding inheritance.
Here comes the super keyword to the rescue; it helps to call the superclass constructor from a subclass.
Let’s see how does it work?
Example:
// Superclass definitionclass Shape { // Declare variables to store the dimensions double dimension1, dimension2;
// Superclass (Shape) constructor Shape(double dim1, double dim2) { dimension1 = dim1; dimension2 = dim2; }
// Method to calculate the area of the shape double calculateShapeArea() { return dimension1 * dimension2; }}
// Subclass definition that extends the Superclassclass RectangularShape extends Shape { // Subclass (RectangularShape) constructor RectangularShape(double length, double breadth) { // Call the superclass (Shape) constructor super(length, breadth); }}
class Main { public static void main(String[] args) { // Create an object of the RectangularShape class RectangularShape r = new RectangularShape(5, 8); // Calculate and display the area of the shape System.out.println("Area: " + r.calculateShapeArea()); }}
Explanation:
The calculateShapeArea method of the RectangularShape class produces this output. The method calculates the area of the shape using the dimensions dimension1 and dimension2, which are passed to the RectangularShape constructor. Dimension 1 and dimension 2 are initialized to 5 and 8, respectively. Finally, calculate the shape’s area by multiplying these dimensions, resulting in a value of 40.0.
Output:
Area: 40.0
Read: Implementing Array in Java
Conclusion
The above article goes through various uses and implementations of super keywords in Java using examples. We hope the tutorial helped you understand the super keyword better. In addition, if you have any queries, please ask us on the link below and stay tuned for more content on Java Programming.
For more, Read: 8 Most Important Data Structures a Programmer Must Know.
FAQs
When to use super keyword in Java?
1. To access the members of the superclass from within the subclass: We can use the super keyword to access the members of the superclass that have been overridden or hidden by the subclass. 2. To invoke the superclass constructor from within the subclass constructor: When we create a subclass, we can use the super keyword to call the constructor of the superclass, passing the required arguments. This is done to initialize the instance variables of the superclass before initializing the instance variables of the subclass. 3. To resolve ambiguity between a field or method in the subclass and a field or method in the superclass: If a subclass has a field or method with the same name as a field or method in the superclass, we can use the super keyword to specify which field or method we want to access. 4. To access the static members of the superclass from within the subclass: We can use the super keyword to access the static members of the superclass from within the subclass.
How does the super keyword help superclass from getting overridden?
The super keyword does not directly prevent the superclass from being overridden. However, if we use the final keyword to make a method or class final, it cannot be overridden or subclassed.
Where can we use the super keyword in Java?
The super keyword in Java is a reference variable that is used to refer to the immediate superclass of a class. It can be used to access the members (fields, methods, and constructors) of the superclass from within the subclass. The super keyword is an important part of object-oriented programming in Java and is used to allow subclass objects to access the members of their superclass and to allow subclass constructors to initialize the instance variables of their superclass.
What is Super Keyword in Java?
The super keyword in Java is a reference variable that is used to refer to the immediate superclass of a class. It can be used to access the members (fields, methods, and constructors) of the superclass from within the subclass.
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio