CHAPTER 13

image

Overriding

A member in a subclass can redefine a member in its superclass. This is most often done to give instance methods new implementations.

Overriding members

In the example below, Rectangle’s getArea method is overridden in Triangle, by redeclaring it there with the same method signature. The signature includes the name, parameters and return type of the method. However, the access level may be changed to allow for more access than the method being overridden.

class Rectangle{   public int w = 10, h = 10;  public int getArea() { return w * h; }}  class Triangle extends Rectangle{   public int getArea() { return w * h / 2; } ...

Get Java Quick Syntax Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.