(Translated by https://www.hiragana.jp/)
Super Keyword in Java - GeeksforGeeks
Open In App

Super Keyword in Java

Last Updated : 15 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The super keyword in Java is a reference variable that is used to refer to parent class when we’re working with objects. You need to know the basics of Inheritanceand Polymorphism to understand the Java super keyword. 

The Keyword “super” came into the picture with the concept of Inheritance. In this article, we gonna covers all about super in Java including definitions, examples, Uses, Syntax, and more.

Characteristics of Super Keyword in Java

In Java, super keyword is used to refer to the parent class of a subclass. Here are some of its key characteristics:

  • super is used to call a superclass constructor: When a subclass is created, its constructor must call the constructor of its parent class. This is done using the super() keyword, which calls the constructor of the parent class.
  • super is used to call a superclass method: A subclass can call a method defined in its parent class using the super keyword. This is useful when the subclass wants to invoke the parent class’s implementation of the method in addition to its own.
  • super is used to access a superclass field: A subclass can access a field defined in its parent class using the super keyword. This is useful when the subclass wants to reference the parent class’s version of a field.
  • super must be the first statement in a constructor: When calling a superclass constructor, the super() statement must be the first statement in the constructor of the subclass.
  • super cannot be used in a static context: The super keyword cannot be used in a static context, such as in a static method or a static variable initializer.
  • super is not required to call a superclass method: While it is possible to use the super keyword to call a method in the parent class, it is not required. If a method is not overridden in the subclass, then calling it without the super keyword will invoke the parent class’s implementation.

Overall, the super keyword is a powerful tool for subclassing in Java, allowing subclasses to inherit and build upon the functionality of their parent classes.

Use of super keyword in Java

It is majorly used in the following contexts as mentioned below:

  • Use of super with Variables
  • Use of super with Methods
  • Use of super with Constructors

1. Use of super with Variables

This scenario occurs when a derived class and base class have the same data members. In that case, there is a possibility of ambiguity r the JVM

We can understand it more clearly using the following example:

Example

Java




// super keyword in java example
  
// Base class vehicle
class Vehicle {
    int maxSpeed = 120;
}
  
// sub class Car extending vehicle
class Car extends Vehicle {
    int maxSpeed = 180;
  
    void display()
    {
        // print maxSpeed of base class (vehicle)
        System.out.println("Maximum Speed: "
                           + super.maxSpeed);
    }
}
  
// Driver Program
class Test {
    public static void main(String[] args)
    {
        Car small = new Car();
        small.display();
    }
}


Output

Maximum Speed: 120

In the above example, both the base class and subclass have a member maxSpeed. We could access the maxSpeed of the base class in subclass using super keyword.

2. Use of super with Methods

This is used when we want to call the parent class method. So whenever a parent and child class have the same-named methods then to resolve ambiguity we use the super keyword.

This code snippet helps to understand the said usage of the super keyword.

Example

Java




// super keyword in java example
  
// superclass Person
class Person {
    void message()
    {
        System.out.println("This is person class\n");
    }
}
// Subclass Student
class Student extends Person {
    void message()
    {
        System.out.println("This is student class");
    }
    // Note that display() is
    // only in Student class
    void display()
    {
        // will invoke or call current
        // class message() method
        message();
  
        // will invoke or call parent
        // class message() method
        super.message();
    }
}
// Driver Program
class Test {
    public static void main(String args[])
    {
        Student s = new Student();
  
        // calling display() of Student
        s.display();
    }
}


Output

This is student class
This is person class

In the above example, we have seen that if we only call method message() then, the current class message() is invoked but with the use of the super keyword, message() of the superclass could also be invoked.

3. Use of super with constructors

The super keyword can also be used to access the parent class constructor. One more important thing is that ‘super’ can call both parametric as well as non-parametric constructors depending on the situation. 

Following is the code snippet to explain the above concept:

Example 1

Java




// Java Code to show use of
// super keyword with constructor
  
// superclass Person
class Person {
    Person()
    {
        System.out.println("Person class Constructor");
    }
}
  
// subclass Student extending the Person class
class Student extends Person {
    Student()
    {
        // invoke or call parent class constructor
        super();
  
        System.out.println("Student class Constructor");
    }
}
  
// Driver Program
class Test {
    public static void main(String[] args)
    {
        Student s = new Student();
    }
}


Output

Person class Constructor
Student class Constructor

In the above example, we have called the superclass constructor using the keyword ‘super’ via subclass constructor.

Example 2

Java




class ParentClass {
    public boolean isTrue() { return true; }
}
  
class ChildClass extends ParentClass {
    public boolean isTrue()
    {
        // calls parent implementation of isTrue()
        boolean parentResult = super.isTrue();
        // negates the parent result
        return !parentResult;
    }
}
  
public class Main {
    public static void main(String[] args)
    {
        ChildClass child = new ChildClass();
        // calls child implementation
        // of isTrue()
        boolean result = child.isTrue();
  
        // prints "false"
        System.out.println(result);
    }
}


Output

false

Advantages of Using Java Super Keyword

The super keyword in Java provides many advantages in object-oriented programming are as follows:

  • Enables reuse of code: Using the super keyword allows subclasses to inherit functionality from their parent classes, which promotes the reuse of code and reduces duplication.
  • Supports polymorphism: Because subclasses can override methods and access fields from their parent classes using super, polymorphism is possible. This allows for more flexible and extensible code.
  • Provides access to parent class behaviour: Subclasses can access and use methods and fields defined in their parent classes through the super keyword, which allows them to take advantage of existing behaviour without having to reimplement it.
  • Allows for customization of behaviour: By overriding methods and using super to call the parent implementation, subclasses can customize and extend the behaviour of their parent classes.
  • Facilitates abstraction and encapsulation: The use of super promotes encapsulation and abstraction by allowing subclasses to focus on their behaviour while relying on the parent class to handle lower-level details.

Overall, the super keyword is a key feature of inheritance and polymorphism in Java, and it provides several benefits for developers seeking to write reusable, extensible, and well-organized code.

Important Points to Remember While Using “Java Super Keyword”

Here are some Important points that you need to take care of during using super keywords in Java:

  • Call to super() must be the first statement in the Derived(Student) Class constructor because if you think about it, it makes sense that the superclass has no knowledge of any subclass, so any initialization it needs to perform is separate from and possibly prerequisite to any initialization performed by the subclass. Therefore, it needs to complete its execution first.
  • If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the superclass does not have a no-argument constructor, you will get a compile-time error. The object does have such a constructor, so if the Object is the only superclass, there is no problem.

super Keyword in Java

  • If a subclass constructor invokes a constructor of its superclass, either explicitly or implicitly, you might think that a whole chain of constructors is called, all the way back to the constructor of Object. This, in fact, is the case. It is called constructor chaining.

FAQs – Java super Keyword

Q1. What is super () and super keyword in Java?

Super() is a Java keyword used to call a superclass constructor. Super accesses superclass members and maintains inheritance hierarchies.

Q2. Which is the super class of Java?

The Object class aka super class is at the top of the class hierarchy in Java’s java.lang package. Every class, whether predefined or user-defined, is a subclass of the Object class.

Q3. Why is Super important in Java?

super is essential in Java as it facilitates the access, initialization, and management of relationships between superclasses and subclasses, thereby promoting code reusability.



Previous Article
Next Article

Similar Reads

Difference between super and super() in Java with Examples
In java it is predefined that the 'super' word is somewhere related to the parent class. If we need to brief and justify the title in one go then the super keyword in java refers to dealing with parent class object while super() deals with parent class constructor. We will be covering the article first discussing the concept of a super keyword foll
4 min read
Using the super Keyword to Call a Base Class Constructor in Java
We prefer inheritance to reuse the code available in existing classes. In Java, Inheritance is the concept in which one class inherits the properties of another class. In the below example there are two classes Programming and DP while Programming is Parent class and DP is child class. From the main class, we have created an object of DP i.e. child
5 min read
super keyword for Method Overloading in Java
We use Method overloading to use a similar method for more than one time. This can be achieved by using different parameters in the signature. In the below example a class GFG with three similar methods is available, though the three methods are overloaded they are provided with different parameters. The object of the class GFG calls a method with
4 min read
Accessing Grandparent’s member in Java using super
Directly accessing Grandparent's member in Java: Predict the output of the following Java program. Java Code // filename Main.java class Grandparent { public void Print() { System.out.println("Grandparent's Print()"); } } class Parent extends Grandparent { public void Print() { System.out.println("Parent's Print()"); } } class C
2 min read
Difference between super() and this() in java
super and this keyword super() as well as this() keyword both are used to make constructor calls. super() is used to call Base class's constructor(i.e, Parent's class) while this() is used to call the current class's constructor. Let us see both of them in detail: super() Keyword super() is used to call Base class's(Parent class's) constructor. Jav
7 min read
super and this keywords in Java
In java, super keyword is used to access methods of the parent class while this is used to access methods of the current class. this keyword is a reserved keyword in java i.e, we can't use it as an identifier. It is used to refer current class's instance as well as static members. It can be used in various contexts as given below: to refer instance
7 min read
Comparison of static keyword in C++ and Java
Static keyword is used for almost the same purpose in both C++ and Java. There are some differences though. This post covers similarities and differences of static keyword in C++ and Java. Similarities between C++ and Java for Static KeywordStatic data members can be defined in both languages.Static member functions can be defined in both languages
6 min read
var keyword in Java
The var reserved type name (not a Java keyword) was introduced in Java 10. Type inference is used in var keyword in which it detects automatically the datatype of a variable based on the surrounding context. The below examples explain where var is used and also where you can't use it. 1. We can declare any datatype with the var keyword. Java Code /
4 min read
Usage of Enum and Switch Keyword in Java
An Enum is a unique type of data type in java which is generally a collection (set) of constants. More specifically, a Java Enum type is a unique kind of Java class. An Enum can hold constants, methods, etc. An Enum keyword can be used with if statement, switch statement, iteration, etc. enum constants are public, static, and final by default.enum
4 min read
Usage of Break keyword in Java
Break keyword is often used inside loops control structures and switch statements. It is used to terminate loops and switch statements in java. When the break keyword is encountered within a loop, the loop is immediately terminated and the program control goes to the next statement following the loop. When the break keyword is used in a nested loop
6 min read
Protected Keyword in Java with Examples
Access modifiers in Java help to restrict the scope of a class, constructor, variable, method, or data member. There are four types of access modifiers available in java. The access of various modifiers can be seen in the following table below as follows:  The protected keyword in Java refers to one of its access modifiers. The methods or data memb
5 min read
volatile Keyword in Java
Using volatile is yet another way (like synchronized, atomic wrapper) of making class thread-safe. Thread-safe means that a method or class instance can be used by multiple threads at the same time without any problem. Consider the below example. class SharedObj { // Changes made to sharedVar in one thread // may not immediately reflect in other th
5 min read
transient keyword in Java
transient is a variables modifier used in serialization. At the time of serialization, if we don't want to save value of a particular variable in a file, then we use transient keyword. When JVM comes across transient keyword, it ignores original value of the variable and save default value of that variable data type. transient keyword plays an impo
3 min read
instanceof Keyword in Java
In Java, instanceof is a keyword used for checking if a reference variable contains a given type of object reference or not. Following is a Java program to show different behaviors of instanceof. Henceforth it is known as a comparison operator where the instance is getting compared to type returning boolean true or false as in Java we do not have 0
4 min read
return keyword in Java
In Java, return is a reserved keyword i.e., we can't use it as an identifier. It is used to exit from a method, with or without a value. Usage of return keyword as there exist two ways as listed below as follows:  Case 1: Methods returning a valueCase 2: Methods not returning a valueLet us illustrate by directly implementing them as follows: Case 1
6 min read
strictfp keyword in java
In Java, the strictfp is a modifier that stands for strict floating-point which was not introduced in the base version of Java as it was introduced in Java version 1.2. It is used in Java for restricting floating-point calculations and ensuring the same result on every platform while performing operations in the floating-point variable. Floating-po
2 min read
abstract keyword in java
In Java, abstract is a non-access modifier in java applicable for classes, and methods but not variables. It is used to achieve abstraction which is one of the pillars of Object Oriented Programming(OOP). Following are different contexts where abstract can be used in Java. Characteristics of Java Abstract KeywordIn Java, the abstract keyword is use
7 min read
Native Keyword in Java
The native keyword in Java is applied to a method to indicate that the method is implemented in native code using JNI (Java Native Interface). The native keyword is a modifier that is applicable only for methods, and we can’t apply it anywhere else. The methods which are implemented in C, C++ are called native methods or foreign methods. The native
4 min read
final Keyword in Java
The final method in Java is used as a non-access modifier applicable only to a variable, a method, or a class. It is used to restrict a user in Java. The following are different contexts where the final is used: VariableMethodClass The final keyword is used to define constants or prevent inheritance in Java. To understand how and when to use final
12 min read
static Keyword in Java
The static keyword in Java is mainly used for memory management. The static keyword in Java is used to share the same variable or method of a given class. The users can apply static keywords with variables, methods, blocks, and nested classes. The static keyword belongs to the class rather than an instance of the class. The static keyword is used f
9 min read
Can String be considered as a Keyword?
Is string a keyword? A string is NOT a keyword. It is one of the names of data types declared in the standard library. How to check if a string is a keyword in C++? In C++ there is no special method to check whether the given string is a keyword or not. But there are a set of keywords present which is listed below-"auto", "break", "case", "char", "
5 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
java.lang.Math.atan2() in Java
atan2() is an inbuilt method in Java that is used to return the theta component from the polar coordinate. The atan2() method returns a numeric value between -[Tex]\pi [/Tex]and [Tex]\pi [/Tex]representing the angle [Tex]\theta [/Tex]of a (x, y) point and the positive x-axis. It is the counterclockwise angle, measured in radian, between the positiv
1 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg