One
of the most compelling features about Java is code reuse.
But to be revolutionary, you’ve got to be able to do a lot more than copy
code and change it.
That’s
the approach used in procedural languages like C, and it hasn’t worked
very well. Like everything in Java, the solution revolves around the class. You
reuse code by creating new classes, but instead of creating them from scratch,
you use existing classes that someone has already built and debugged.
The
trick is to use the classes without soiling the existing code. In this chapter
you’ll see two ways to accomplish this. The first is quite
straightforward: You simply create objects of your existing class inside the
new class. This is called
compositionbecause
the new class is composed of objects of existing classes. You’re simply
reusing the functionality of the code, not its form.
The
second approach is more subtle. It creates a new class as a
type
of
an existing class. You literally take the form of the existing class and add
code to it without modifying the existing class. This magical act is called
inheritance,
and the compiler does most of the work. Inheritance is one of the cornerstones
of object-oriented programming and has additional implications that will be
explored in the next chapter.
It
turns out that much of the syntax and behavior are similar for both composition
and inheritance (which makes sense because they are both ways of making new
types from existing types). In this chapter, you’ll learn about these
code reuse mechanisms.