Java Reference
In-Depth Information
Figure 9.4. Multiple behavior composition
Here's another advantage of defining simple interfaces with default implementations like the
ones for your game. Let's say you need to modify the implementation of moveVertically to make
it more efficient. You can now change its implementation directly in the Moveable interface, and
all classes implementing it will automatically inherit the code (provided they didn't implement
the method themselves)!
Inheritance considered harmful
Inheritance shouldn't be your answer to everything when it comes down to reusing code. For
example, inheriting from a class that has 100 methods and fields just to reuse one method is a
bad idea, because it adds unnecessary complexity. You'd be better off using delegation : create a
method that calls directly the method of the class you need via a member variable. This is why
you'll sometime find classes that are declared “final” intentionally: they can't be inherited from
to prevent this kind of antipattern or have their core behavior messed with. Note that sometimes
final classes have a place; for example, String is final because we don't want anybody to be able
to interfere with such core functionality.
The same idea is applicable to interfaces with default methods. By keeping your interface
minimal, you can achieve greater composition because you can select only the implementations
you need.
Search WWH ::




Custom Search