Skip to main content
Advertisement

7.6 The 'super' Keyword and super()

When a child class inherits from a parent class, it can use the parent's variables and methods. However, sometimes you need to explicitly refer to the original parent methods, even after they have been overridden. This is when you use the super keyword.

1. The Reference Variable super

Just like this points to the current object instance, super points to the parent object. It is used to resolve naming conflicts between parent and child variables.

class Parent {
int x = 10;
}

class Child extends Parent {
int x = 20;

void method() {
System.out.println("x=" + x); // Child's local x (20)
System.out.println("this.x=" + this.x); // Child's instance x (20)
System.out.println("super.x=" + super.x); // Parent's inherited x (10)
}
}

Calling Original Parent Methods

When you override a method but still want to use the parent's logic, super prevents code duplication.

class Point3D extends Point {
int z;

@Override
String getLocation() {
// Run the parent logic first, then append child logic
return super.getLocation() + ", z :" + z;
}
}

2. Parent Constructor Invocation super()

When creating an instance of a child class, the parent portion must be initialized first. The super() statement performs this function.

  • Rule: You must call super() or this() on the very first line of any constructor.
  • Automatic Insertion: If you do not write it, the compiler automatically inserts an empty super(); at the first line.
class Point {
int x, y;

Point(int x, int y) {
this.x = x;
this.y = y;
}
}

class Point3D extends Point {
int z;

Point3D(int x, int y, int z) {
super(x, y); // Must explicitly call parent constructor because default constructor is missing
this.z = z;
}
}

Summary

  • super: Reference variable pointing to the parent. Used to force access to parent members.
  • super(): Command to call the parent's constructor. Must be on the first line.
Advertisement