Java Reference
In-Depth Information
We can start by defining a base class,
Element
, from which we'll derive the classes defining specific
types of shapes. The
Element
class will have data members that are common to all types of shapes, and
we can put the methods that we want to execute polymorphically in this class too. All we need to do is
make sure that each shape class that is derived from the
Element
class has its own implementation of
these methods.
The diagram shows the initial members that we will declare in the
Element
base class. The only data
member for now is the
color
member to store the color of a shape. The
getShape()
and
getBounds()
methods will be
abstract
here since the
Element
class is not intended to define a
shape, but we will be able to implement the
getColor()
method in this class. The other methods will
be implemented by the subclasses of
Element
.
Initially, we'll define the five classes shown in the diagram that represent shapes, with the
Element
class as a base. They provide objects that represent straight lines, rectangles, circles, freehand curves
and blocks of text. These classes will all inherit the data members that we define for the
Element
class.
As you can see from the names of our shape classes, they are all nested classes to the class
Element
.
The
Element
class will serve as the base class, as well as house our shape classes. This will avoid any
possible confusion with other classes that might have names such as
Line
or
Circle
for instance.
Since there will be no
Element
objects around, we will declare our shape classes as static members of
the
Element
class.
We can now define the base class,
Element
. Note that this won't be the final version, as we'll be adding
more functionality in later chapters. Here's the code that needs to go in
Element.java
in the
Sketcher directory:
import java.awt.Color;
import java.awt.Shape;
public abstract class Element {
public Element(Color color) {
this.color = color;
}
public Color getColor() {
return color;
}
public abstract Shape getShape();