Overriding Methods

Inheritance

Overriding Methods

🙋 Need help? Ask an expert now!

Overriding is an important concept when dealing with inheritance. A subclass' method overrides a superclass' method when it has the same signature, meaning it has the same name and the same parameters. See an example of how you can override a superclass' method below.

OverrideMethodTestOne.java
package exlcode;

public class OverrideMethodTestOne {

  public String exampleVariableOne = "Java";

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

public class OverrideMethodTestTwo extends OverrideMethodTestOne {

  public String exampleVariableTwo = "World";

  // overrides the print method from OverrideMethodTestOne
  public void print() {
    // calls the print method from the OverrideMethodTestOne
    super.print();
    System.out.println(exampleVariableTwo);
  }
}
OverridingMethodsExample.java
package exlcode;

public class OverridingMethodsExample {

  public static void main(String[] args) {
    OverrideMethodTestOne objectOne = new OverrideMethodTestTwo();
    objectOne.print();
  }
}

The method print() exists in the subclass and superclass with the same signature, and is overridden by the subclass as shown above. The reason why the subclass OverrideMethodTwo overrides the method print() is because it wants to print the extra String "World" on the console. When the statements OverrideMethodTestOne objectOne = new OverrideMethodTestTwo(); and objectOne.print() are called, the program first searches for the print() method in the class OverrideMethodTestTwo before it looks for the print() method in the superclass, which is why the print() method in the subclass is used. If the print() method was not overridden in the subclass, only "Java" would end up being printed to the console.

Edit Me on GitHub!

Application Question

Consider the following class declarations:

public class Food{
  public void print(){
    System.out.print("Food");
  }
}

public class Bread extends Food
{
  public void print()
  {
    System.out.print("Bread");
  }
}

What is printed as a result of executing the following code segment?

Food varOne = new Bread();
varOne.print();