How to Add Buttons and Text to Your JavaFX Project
How to Use the sort Method for Quicksort in Java
Java: Use Simple If Statements

How to Override Methods in Java

If a subclass declares a method that has the same signature as a public method of the base class in Java, the subclass version of the method overrides the base class version of the method. This technique lets you modify the behavior of a base class to suit the needs of the subclass.

Suppose you have a base class named Game that has a method named play. The base class, which doesn’t represent any particular game, implements this method:

public class Game
 public void play()

Then you declare a class named Chess that extends the Game class but also provides an implementation for the play method:

public class Chess extends Game
 public void play()
  System.out.println("I give up. You win.");

Here, when you call the play method of a Chess object, the game announces that it gives up.

Note that to override a method, three conditions have to be met:

  • The class must extend the class that defines the method you want to override.

  • The method must be declared in the base class with public access. You can’t override a private method.

  • The method in the subclass must have the same signature as the method in the base class. In other words, the name of the method and the parameter types must be the same.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
What Is Jakarta Struts?
Making Sense of Java's API Documentation
How to Use Lambda Expressions to Handle Events in Java
10 Bits of Advice for New Software Developers
How to Use the Delegation Pattern in Java