AlgoViz

Method overriding

medium 45 min

A subclass gives its own body to a method that the parent already has.

Watch lesson4:42

Where it shows up

The same pattern appears across everyday software.

  • Java Object

    equals, hashCode and toString are there to be overridden. The documentation states the contract: reflexive, symmetric, transitive, consistent, and equal objects have equal hash codes.

  • Java LinkedHashMap

    removeEldestEntry may be overridden to impose a policy for removing stale entries. A few lines make a small cache.

  • Jakarta HttpServlet

    A subclass overrides at least one method, usually doGet or doPost. The servlet container calls it.

  • Android Activity

    The reference says for several methods: if you override this method you must call through to the superclass implementation.

  • Django models

    You can override save. The documentation warns: forget the superclass method, and the object is not saved.

  • Python json

    Subclass JSONEncoder and override default for your own types. For other objects call the base implementation, which raises TypeError.

  • Python HTMLParser

    Subclass it and override its methods such as the one for start tags. The parser calls them while it reads.

  • Python unittest

    TestCase calls setUp and tearDown around every test. Both are hooks with an empty default.

  • TypeScript

    With noImplicitOverride the compiler demands the word override, so that renaming a parent's method shows every child.

  • Java Override annotation

    Compilers must report an error if the marked method does not override or implement a method of a supertype (or a public method of Object).