Radford University ITEC

ITEC120-ibarland (incl. office hrs)infolectureslabshwsjava.lang docsjava.util docs

Inheritance

Interface vs. abstract class

The first two are an advantage to abstract classes, but the second two are an advantage to interfaces. We'll come back to this topic below, trying to get the best of both worlds.


The Delegate Pattern

How to fake multiple inheritance, if Java doesn't allow it? That is, suppose we have Guard Dogs, which are like Dogs but they have some additional guard behaviours:

  String threatenSound();             // How does this guard threaten?
  boolean deters(Animal anAnimal);    // Does this guard succesfully deter anAnimal?
In fact, we quickly realize that being a guard is not specific to being a Dog; we could certainly have guard-cats and guard-pythons. In fact, some guards aren't even animals -- an alarm system can make a threatening sound and can deter some (human) animals. So we should have Guard be its own class. (There is code for the Guard methods.

But now we have the problem, that for a class GuardDog we want to Extend two different classes.

This is better, but not a perfect solution. For instance: And, if we want to make a SmallGuardDog, what class should it extend — GuardDog, or SmallDog? Either answer is unsatisfactory. Delegate pattern can still help, though it's starting to become cumbersome: for every class we can have an interface, and then have SmallGuardDog extend SmallDog implement IGuardDog2, and it will have a GuardDog2 delegate instance inside of it. This avoids repeated code (at the cost of our mental overhead).

ITEC120-ibarland (incl. office hrs)infolectureslabshwsjava.lang docsjava.util docs


©2006, Ian Barland, Radford University
Last modified 2006.Dec.10 (Sun)
Please mail any suggestions
(incl. typos, broken links)
to ibarlandradford.edu
Powered by PLT Scheme