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
Advertisement

Inside Dummies.com