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 ...
Get Java in a Nutshell, 5th 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.