Subclasses and Inheritance
The Circle
defined earlier is a simple class
that distinguishes circle objects only by their radii. Suppose,
instead, that we want to represent circles that have both a size and
a position. For example, a circle of radius 1.0 centered at point 0,0
in the Cartesian plane is different from the circle of radius 1.0
centered at point 1,2. To do this, we need a new class, which
we’ll call PlaneCircle.
We’d like to add the ability to represent the
position of a circle without losing any of the existing functionality
of the Circle class. This is done by defining
PlaneCircle as a subclass of
Circle so that PlaneCircle
inherits the fields and methods of its superclass,
Circle. The ability to add functionality to a
class by subclassing, or extending, is central to the object-oriented
programming paradigm.
Extending a Class
Example 3-3
shows how we can implement
PlaneCircle as a subclass of the
Circle class.
Example 3-3. Extending the Circle class
public class PlaneCircle extends Circle { // We automatically inherit the fields and methods of Circle, // so we only have to put the new stuff here. // New instance fields that store the center point of the circle public double cx, cy; // A new constructor method to initialize the new fields // It uses a special syntax to invoke the Circle() constructor public PlaneCircle(double r, double x, double y) { super(r); // Invoke the constructor of the superclass, Circle() this.cx = x; // Initialize the instance field cx this.cy ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access