Bruce Eckel’s Thinking in Java | Contents | Prev | Next |
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.
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.
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
composition
because
the new class is composed of objects of existing classes. You’re simply
reusing the functionality of the code, not its form.
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.