Java Fundamentals  «Prev  Next»
Lesson 6Overriding methods
ObjectiveOverride methods.

Overriding methods in Java

You can do some pretty interesting things with methods. One notable OOP feature is the ability to override methods, which involves replacing an inherited method with a newer version. As an example, the Predator class might define a hunt() method that specifies how a generic predator hunts:

class Predator {
...
  void hunt() {
    // hunt some prey
    System.out.println("I'll just sit here
    and wait for something to kill.");
  }
}

You have already seen how the Lion class implements a hunt() method that reflects the hunting style of a lion. In this case, the lion's hunt() method overrides the hunt() method:
class Lion extends Predator {
  int energy;
  int aggression;
  boolean hungry;
  Color color;
  void hunt() {
    // hunt some prey, lion-style
    System.out.println("Roar!!!");
  }
  void eat() {
    if (hungry) {
      // eat
      energy++;
      aggression--;
    }
    else {
      // don't eat
      energy--;
      aggression++;
    }
  }
}

When you call hunt() on a Lion object, the overridden hunt() method is the one executed. Overridden methods are always given precedence within the context of the class in which they are defined.

Overriding Methods - Exercise

Override a method and develop a test program in this exercise.
Overriding Methods - Exercise