Published 09 Sep, 2022

Java - Java "partial" override

Category Java
Modified : Oct 04, 2022
93

When overriding a method in Java is it possible to call the "original" one. For example:

public class A extends B{

  @Override
  public void foo(){
    System.out.println("yep");
    // Then execute foo() as it's defined in B
  }

}

Answers

There are 4 suggested solutions here and each one has been listed below with a detailed description. The following topics have been covered briefly such as Java, Overriding. These have been categorized in sections for a clear and precise explanation.

28
public class A extends B{

  @Override
  public void foo(){
    System.out.println("yep");
    super.foo(); // calls the method implemented in B
  }  
}

36

You are looking for super.foo().


35

The use of the Keywork super is meant for this

super.foo();

33

Simply call super.methodName() to call your supertype's version of the method.

public class A extends B{
  @Override
  public void foo(){
    System.out.println("yep");
    super.foo(); // Here you call the supertype's foo()
  }
}

Also, this isn't 'partially' overriding the method. You are fully overriding it, but you are just using some of the parent's functionality.