Java Reference
In-Depth Information
Use of inheritance is prevalent in the Java class libraries. One notable example is in the
drawing of two-dimensional graphics. In this section we'll discuss a class that uses
inheritance to draw complex two-dimensional shapes and to assign colors to them.
In the Chapter 3 supplement on graphics, we introduced an object called
Graphics
which acts like a pen that you can use to draw shapes and lines onto a win-
dow. When Java's designers wanted additional graphical functionality, they extended
the
Graphics
class into a more powerful class called
Graphics2D
. This is a good
example of one of the more common uses of inheritance: to extend and reuse func-
tionality from a powerful existing object.
Why didn't Sun simply add the new methods into the existing
Graphics
class?
The
Graphics
class already worked properly, so Sun decided it was best not to per-
form unnecessary surgery on it. John Vlissides, part of a famous foursome of soft-
ware engineers affectionately called the “Gang of Four,” once described the idea this
way: “A hallmark—if not the hallmark—of good object-oriented design is that you
can modify and extend a system by adding code rather than by hacking it. In short,
change is additive, not invasive.”
Making
Graphics2D
extend
Graphics
retains
backward compatibility.
Backward
compatibility is the ability of new code to work correctly with old code without mod-
ifying the old code. Leaving
Graphics
untouched ensured that old programs would
keep working properly and gave new programs the option to use the new
Graphics2D
functionality.
Sun's documentation for
Graphics2D
describes the purpose of the class as fol-
lows. “This
Graphics2D
class extends the
Graphics
class to provide more sophisti-
cated control over geometry, coordinate transformations, color management, and text
layout. This is the fundamental class for rendering 2-dimensional shapes, text, and
images on the Java™ platform.” To be specific,
Graphics2D
adds the ability to per-
form transformations such as scaling and rotation when you're drawing. These capa-
bilities can lead to some fun and interesting images on the screen.
If you used the
DrawingPanel
class from Chapter 3's graphical supplement, you
previously wrote statements like the following to get access to the panel's
Graphics
object:
Graphics g = panel.getGraphics();
Actually, the
getGraphics
method doesn't return a
Graphics
object at all, but
rather a
Graphics2D
object. Because of polymorphism, though, it is legal for your
program to treat it as a
Graphics
object, because every
Graphics2D
object “is” a
Graphics
object. To use it as a
Graphics2D
object instead, simply write the follow-
ing line of code:
Graphics2D g2 = panel.getGraphics();
Search WWH ::
Custom Search