This week we'll continue our improved robots example. The main new tool for organizing our code will be the concept of abstract classes, which give us a concept that kind of lies inbetween interfaces and class inheritance.
Abstract classes provide the same concept as an interface, but the abstract class can provide implementations for some (but not necessarily all) methods. In addition, abstract classes can have instance data members. In this way, you can specify the behavior for part of the class, and require subclasses to implement the rest. So we have 3 ways of structuring class relationships that fall under the general concept of inheritance:
- Implementing interfaces: specifying only the method signatures (and
static
final
data members) for a class. - Inheriting from an abstract class: specifying the method signatures,
data members, and some of the method implementations. The
abstract
methods give a way to indicate which methods must be different in each subclass. - Inheriting from a (fully defined) class: specifying the method signatures, data members, and all of the method implementations. Since all methods are defined in the parent class, there is no direct indication of which (if any) methods should have different implementations in subclasses.
In our example, we'll use an abstract class CharacterBase
to implement common
functionality for all of our characters, and then inherit from that class when
we make the fully-defined characters.