However, the child class may never distinguish itself from its parent by deleting or removing a field or method defined in the parent. This restriction ensures that the child class will always have at least as much capability as its parent, and never less.
For example, consider the Ship class:
public class Ship { // class declaration
// Field Variables:
private HullCharacteristics charac; // dimensions and coefficients
private HullGeometry geom; // explicit shape
// Field Access Methods:
public void setGeometry ( // method to set the hull geometry
HullGeometry geo_value) { // argument supplying new geometry coordinates
geom = geo_value; // set the field to the supplied coordinates
} // end of setGeometry() method
// method to get the hull geometry
public HullGeometry getGeometry () {
return geom; // give the hull geometry to the caller
} // end of getGeometry() method
} // end of class
The Ship class can then be used as a basis for the creation of classes
that model special kinds of ships, such as CargoShip:
public class CargoShip // cargo ship class declaration
extends Ship { // defined as a specialization of Ship
// Field Variables:
private Cargo wheat; // cargo ship payload
// Field Access Methods:
public void setCargo ( // method to load the cargo
Cargo new_payload) { // argument supplying new cargo data
wheat = new_payload; // set the field to the supplied data
} // end of setCargo() method
// method to inquire about the cargo
public Cargo getCargo () {
return wheat; // give the cargo data to the caller
} // end of getCargo() method
} // end of class
Because CargoShip is defined relative to Ship, the fields and methods in
the CargoShip class definition include those defined in the Ship class;
i.e., the child class "inherits" (automatically includes) all fields and
methods defined in its parent class. So, for example, one can say with
complete validity:
CargoShip Mary_Deare = new CargoShip(); // create cargo ship Mary Deare
Mary_Deare.getGeometry(); // get Mary Deare's hull shape
because CargoShip contains all the fields and methods of Ship.
They are not specified in the CargoShip class above, however, because
their presence is implied by the 'extends Ship' clause. Thus, the class
definition of a subclass only contains differences (additions and
redefinitions) relative to the parent; it never repeats declarations in
the parent.This leads to the major benefits of inheritance. Because declarations in the parent are not repeated in the child, the amount of explicit code in the child class definition is substantially reduced. This simplifies program construction. Also, any changes later made to the parent are automatically assumed to apply to all child classes; the child classes need not be modified at all to obtain changes to the parent. This simplifies program maintenance.