Chapter 17. Advanced Topics
When we first looked at inheritance in Chapter 14, our purpose was to avoid duplicating code. We noticed that decks of cards and hands of cards had common functionality, and we designed a CardCollection
class to provide it. This technique is an example of generalization. By generalizing the code, we were able to reuse it in the Deck
and Hand
classes.
In Chapter 15, we looked at inheritance from a different point of view. When designing GridCanvas
to represent a grid of cells, we extended Canvas
and overrode its paint
method. This design is an example of specialization. Using the code provided by Canvas
, we created a specialized subclass with minimal additional code.
We didn’t write the code for Canvas
; it’s part of the Java library. But we were able to customize it for our own purposes. In fact, the Canvas
class was explicitly designed to be extended.
In this chapter, we’ll explore the concept of inheritance more fully and explore event-driven programming. We’ll continue to develop graphical simulations as a running example, but this time in varying shapes and colors!
Polygon Objects
The word polygon means many angles; the most basic polygons are triangles (three angles), rectangles (four angles), pentagons (five angles), and so forth. Polygons are an important part of computer graphics because they are used to compose more complex images.
Java provides a Polygon
class (in java.awt
) that we can use to represent and draw polygons. The following code creates ...
Get Think Java, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.