Java super keyword

In this chapter you will learn:

  1. What is super keyword
  2. How to use super to call superclass constructors
  3. How to use super to reference members from parent class

Description

You can use super in a subclass to refer to its immediate superclass. super has two general forms.

  1. The first calls the superclass' constructor.
  2. The second is used to access a member of the superclass.

Call superclass constructors

To call a constructor from its superclass:


super(parameter-list);
  • parameter-list is defined by the constructor in the superclass.
  • super(parameter-list) must be the first statement executed inside a subclass' constructor.

Here is a demo for how to use super to call constructor from parent class.

 
class Box {//w  w  w .  ja  v a2  s . c  o m
  private double width;
  private double height;
  private double depth;

  Box(Box ob) { // pass object to constructor
    width = ob.width;
    height = ob.height;
    depth = ob.depth;
  }
  Box(double w, double h, double d) {
    width = w;
    height = h;
    depth = d;
  }
  double volume() {
    return width * height * depth;
  }
}
class BoxWeight extends Box {
  double weight; // weight of box
  BoxWeight(Box ob) { // pass object to constructor
    super(ob);
  }
}
public class Main {
  public static void main(String args[]) {
    Box mybox1 = new Box(10, 20, 15);
    BoxWeight myclone = new BoxWeight(mybox1);
    double vol;

    vol = mybox1.volume();
    System.out.println("Volume of mybox1 is " + vol);
  }
}

This program generates the following output:


Volume of mybox1 is 3000.0

Reference members from parent class

We can reference member variable from parent class with super keyword. Its general form is:


super.member

member can be either a method or an instance variable.

Let's look at the following code.

 
class Base {// w w  w .  j  a v  a  2s.  c o m
  int i;
}
class SubClass extends Base {
  int i; // this i hides the i in A
  SubClass(int a, int b) {
    super.i = a; // i in A
    i = b; // i in B
  }
  void show() {
    System.out.println("i in superclass: " + super.i);
    System.out.println("i in subclass: " + i);
  }
}
public class Main {
  public static void main(String args[]) {
    SubClass subOb = new SubClass(1, 2);
    subOb.show();
  }
}

This program displays the following:

Next chapter...

What you will learn in the next chapter:

  1. How to override a method from parent class
  2. Example - Java Method Overriding
  3. How to use super to access the overridden method
  4. When to overload method and when to override method