Inheritance

Super

🙋 Need help? Ask an expert now!

When implementing inheritance, use the Java reserved word super to call a method in the superclass or to invoke the constructor of the superclass. Remember that private methods cannot be accessed by the subclass. Take a look below to see how super is used.

SuperExample.java
package exlcode;

public class SuperExample {

  public static void main(String[] args) {
    SuperTestTwo superTestTwo = new SuperTestTwo(10,20);
  }
}
SuperTestOne.java
package exlcode;

public class SuperTestOne {

  public int exampleVariableOne = 10;

  public SuperTestOne(int parameterOne) {
    this.exampleVariableOne = parameterOne;
  }

  public void print(){
    System.out.println(exampleVariableOne);
  }
}
SuperTestTwo.java
package exlcode;

public class SuperTestTwo extends SuperTestOne {

  public SuperTestTwo(int parameterOne, int parameterTwo) {
    super(parameterOne);
    super.print();
  }
}

The word super is usually used to call the constructor, but could also be used to call methods. When you start using inheritance in the future, you will most likely be using super more for invoking constructors of the superclass. In the code above, SuperTestTwo invokes the constructor of its superclass SuperTestOne and sets parameterOne directly from the superclass. Therefore, when the print() method is called in the SuperTestTwo class, it prints 10.

Remember that super(); has to be the first statement in the subclass' constructor. Otherwise, you will get a compile-time error. Also, if you extend a class without a zero-argument constructor, like SuperTestTwo above, make sure to use one of the superclass' constructors and have the same parameters. Another data type in the parameter would cause an error. But, if the constructor in the superclass has no arguments(parameters), Java will automatically call one for you in the subclass, so super(); will not be necessary in that case.

Application Question

Consider the following class declarations:

public class Vehicle
            {
              private int varOne;
              public Vehicle(){ 
                varOne = 0; 
              }
              public Vehicle (int paramOne){ 
                varOne = paramOne; 
              }
            }
            
            public class Car extends Vehicle
            {
              public Car(){ 
                super(0); 
              }
            }
            

Which of the following statements will NOT compile?