Table of Contents
ToggleIn object-oriented programming, inheritance is a cornerstone concept that allows subclasses to derive properties and behaviors from their parent classes. One powerful feature that enhances the utility of inheritance in Java is the super keyword. This keyword serves as a bridge between a subclass and its superclass, enabling developers to invoke superclass constructors and methods directly. The super keyword eliminates redundancy, promotes clean code, and simplifies subclass implementation.
In this blog, we will dive deep into the concept of the super keyword, its use cases, and how it optimizes your Java programs. By the end of this article, you will understand how to leverage this feature to write efficient and maintainable code.
The super keyword in Java is used to refer to the immediate superclass of a subclass. It allows access to:
Superclass Constructors: Using super()
to invoke a superclass constructor from within a subclass constructor.
Superclass Methods: Calling a superclass method that has been overridden in the subclass.
Superclass Fields: Accessing fields of the superclass when they are shadowed by subclass fields.
With these functionalities, the super keyword becomes a vital tool in managing inheritance hierarchies.
When a subclass object is created, its constructor often needs to initialize variables inherited from the superclass. By default, Java implicitly calls the no-argument constructor of the superclass if no explicit call to a superclass constructor is made. However, when a specific superclass constructor is required, the super keyword comes into play.
Consider a class hierarchy involving a generic Quadrilateral
class and a more specific Rectangle
class.
/** Represents a quadrilateral */
public class Quadrilateral {
double sideOne;
double sideTwo;
double sideThree;
double sideFour;
/** Constructs a quadrilateral with given side lengths */
public Quadrilateral(double sideOne, double sideTwo, double sideThree, double sideFour) {
this.sideOne = sideOne;
this.sideTwo = sideTwo;
this.sideThree = sideThree;
this.sideFour = sideFour;
}
}
/** Represents a rectangle */
public class Rectangle extends Quadrilateral {
/** Constructs a rectangle using length and width */
public Rectangle(double length, double width) {
super(length, width, length, width);
}
}
In this example, the Rectangle
class constructor uses super(length, width, length, width)
to call the Quadrilateral
class constructor, passing the appropriate values. Without this call, the subclass would have to reimplement the logic of initializing its sides, leading to code duplication.
The super keyword can also be used to call methods from the superclass. This is particularly useful when overriding methods in a subclass but still needing to retain some functionality from the superclass implementation.
super
Let’s extend the Rectangle
class by overriding the isEquivalent()
method while reusing the implementation from the Quadrilateral
class.
/** Represents a rectangle */
public class Rectangle extends Quadrilateral {
/** Makes a rectangle given a length and width */
public Rectangle(double length, double width) {
super(length, width, length, width);
}
/** Determines whether a rectangle is equivalent */
public boolean isEquivalent(double length, double width) {
return super.isEquivalent(length, width, length, width);
}
}
In this code:
The Rectangle
class overrides the isEquivalent()
method.
The super.isEquivalent()
call reuses the implementation of the isEquivalent()
method in the Quadrilateral
class.
This approach ensures that the Rectangle
class inherits the functionality of its superclass while maintaining the flexibility to extend or modify it.
Code Reusability: By invoking superclass methods and constructors, the super keyword eliminates the need to rewrite code.
Clean Inheritance: It maintains a clear relationship between a subclass and its superclass, improving readability and maintainability.
Avoiding Redundancy: Prevents duplicating logic in subclasses by reusing superclass implementations.
Ease of Maintenance: Changes made to the superclass propagate automatically to subclasses through the super keyword.
Polymorphism often involves using superclass references to manage subclass objects. The super keyword plays a crucial role in ensuring that superclass-specific behavior is retained while leveraging subclass-specific implementations.
public class Vehicle {
public void accelerate() {
System.out.println("The vehicle accelerates.");
}
}
public class Car extends Vehicle {
@Override
public void accelerate() {
super.accelerate();
System.out.println("The car accelerates with enhanced features.");
}
}
public class Main {
public static void main(String[] args) {
Vehicle myCar = new Car();
myCar.accelerate();
}
}
Output:
The vehicle accelerates.
The car accelerates with enhanced features.
Here:
The Car
class overrides the accelerate()
method.
The super.accelerate()
call invokes the Vehicle
class implementation before executing the additional logic specific to the Car
class.
This demonstrates how the super keyword integrates superclass functionality within subclass methods.
Use Explicitly When Required: Only use super
when superclass functionality needs to be invoked explicitly. Avoid redundant use.
Avoid Excessive Dependence: While the super keyword promotes reusability, ensure that subclasses have their own distinct behavior to avoid tightly coupling them to superclasses.
Override Judiciously: Use method overriding strategically to extend functionality, not just to replicate superclass behavior.
Calling Nonexistent Superclass Methods: Ensure that the method being invoked with super
exists in the superclass. Otherwise, a compile-time error will occur.
Accessing Private Members: The super keyword cannot access private members of the superclass. Use protected or public visibility as appropriate.
Forgetting to Use super()
in Subclass Constructors: Always explicitly call the appropriate superclass constructor if the superclass lacks a no-argument constructor.
The super keyword is an indispensable tool in Java’s inheritance mechanism. It allows developers to:
Reuse constructors and methods from a superclass,
Avoid redundant code,
Enhance polymorphism, and
Maintain a clean, organized codebase.
By understanding and effectively using the super keyword, you can write Java programs that are efficient, modular, and scalable. Whether you are invoking a superclass constructor, calling overridden methods, or managing polymorphic behaviors, the super keyword ensures seamless interaction between your classes.
Master the super keyword, and you master one of the fundamental aspects of Java’s object-oriented programming paradigm!
super
Keyword with Detailed Answerssuper
Keyword in Java?The super
keyword in Java is used to refer to the immediate parent class’s methods, constructors, or variables. It helps access parent class properties that are hidden or overridden in the subclass.
super
Keyword?Accessing parent class methods.
Calling parent class constructors.
Referring to parent class variables that are hidden by subclass variables.
super
to Call a Parent Class Constructor?class Parent {
Parent(String message) {
System.out.println("Parent constructor: " + message);
}
}
class Child extends Parent {
Child() {
super("Hello from Parent");
}
}
super
in Java?The super
keyword is followed by a method or variable name, or used alone to call a parent constructor:
super.methodName();
super.variableName;
super(arguments);
super
Be Used in Static Methods?No, super
cannot be used in static methods because it is tied to an instance of the class and static methods do not belong to any specific instance.
super
is Not Used in a Constructor?If super
is not explicitly used, the compiler automatically inserts a call to the no-argument constructor of the parent class.
super
to Access a Hidden Variable?class Parent {
String name = "Parent";
}
class Child extends Parent {
String name = "Child";
void display() {
System.out.println(super.name); // Accesses Parent's variable
}
}
super
?class Parent {
void display() {
System.out.println("Parent method");
}
}
class Child extends Parent {
void display() {
super.display(); // Calls Parent's method
System.out.println("Child method");
}
}
super
Be Used in a Constructor of an Abstract Class?Yes, super
can be used to call the constructor of an abstract class:
abstract class Parent {
Parent(String message) {
System.out.println(message);
}
}
class Child extends Parent {
Child() {
super("Abstract parent constructor called");
}
}
super
Be Used in Multiple Inheritance in Java?Since Java does not support multiple inheritance with classes, super
only refers to the immediate parent class. For interfaces, the super
keyword refers to the specific interface.
super
?The parent class constructor is always executed before the child class constructor.
super
in a Static Block?No, super
cannot be used in static blocks as it is tied to an instance, and static blocks do not operate on class instances.
super
Be Used to Call a Private Method?No, private methods in the parent class are not accessible using super
because they are not inherited by the subclass.
super
is Used with Parameters?It calls the parent class constructor with the specified arguments.
super
in Multilevel Inheritance?In multilevel inheritance, super
always refers to the immediate parent class:
class Grandparent {
void display() {
System.out.println("Grandparent method");
}
}
class Parent extends Grandparent {}
class Child extends Parent {
void display() {
super.display(); // Calls Parent's method
}
}
super
Be Used in Interfaces?No, super
cannot be directly used in interfaces. However, for default methods in interfaces, InterfaceName.super.methodName()
can be used.
super
Be Used in Copy Constructors?Yes, super
can initialize parent class fields in a copy constructor:
class Parent {
String name;
Parent(String name) {
this.name = name;
}
}
class Child extends Parent {
Child(String name) {
super(name);
}
}
super
in Exception Handling?super
can be used to pass error messages to the parent class constructor in exception classes:
class MyException extends Exception {
MyException(String message) {
super(message);
}
}
super
Used in Polymorphism?super
helps invoke parent class methods when an overridden method is required.
super
Be Used for Method Chaining?Yes, super
can be used to chain methods from the parent class in overridden methods.
super
in a Class with Multiple Constructors?class Parent {
Parent(String message) {
System.out.println(message);
}
}
class Child extends Parent {
Child() {
super("Default message");
}
Child(String message) {
super(message);
}
}
this
and super
?this
: Refers to the current class instance.
super
: Refers to the immediate parent class instance.
this
and super
in the Same Constructor?No, a constructor can only use either this
or super
as the first statement, not both.
super
?Using super
in static contexts.
Forgetting to explicitly call super
when the parent class lacks a default constructor.
super
Be Used in Overloaded Methods?Yes, super
can be used to call parent class methods in overloaded methods.
super
is Used in a Loop?Using super
in a loop repeatedly invokes the parent class method.
super
?Use super
to clarify method calls in complex inheritance hierarchies.
Avoid overusing super
to maintain code readability.
super
Outside of a Method or Constructor?No, super
can only be used inside instance methods or constructors.
super
?Initializing parent class properties in subclasses.
Accessing methods overridden in subclasses to use parent class logic.
super
Calls?Use logging or breakpoints in the parent class methods to trace super
calls.