InheritanceThere are two fundamental mechanisms for building new classes from existing ones: inheritance and aggregation. It makes sense to inherit from an existing class Vehicle to define a class Car, since a car is a vehicle. The class Vehicle has several parts; therefore, it makes sense to define a composite object of class Vehicle that has constituent objects of such classes as Motor, Axle, and GearBox, which make up a vehicle. Inheritance is illustrated by an example that implements a stack of characters that can print its elements on the terminal. This new stack has all the properties and behaviors of the CharStack class, but it also has the additional capability of printing its elements. Given that this printable stack is a stack of characters, it can be derived from the CharStack class. This relationship is shown in Figure The class PrintableCharStack is called the subclass, and the class CharStack is called the superclass. The CharStack class is a generalization for all stacks of characters, whereas the class PrintableCharStack is a specialization of stacks of characters that can also print their elements. class PrintableCharStack extends CharStack { // (1) The PrintableCharStack class extends the CharStack class at (1). Implementing the printStackElements() method in the PrintableCharStack class requires access - to the field stackArray from the superclass CharStack. However, this field is private and therefore not accessible in the subclass. The subclass can access these fields if the accessibility of the fields is changed to protected in the CharStack class. Example 1.3 uses a version of the class CharStack, which has been modified accordingly. Implementation of the printStackElements() method is shown at (2). The constructor of the PrintableCharStack class at (3) calls the constructor of the superclass CharStack - in order to initialize the stack properly. Example 1.3 Defining a Subclass// Source Filename: CharStack.java Objects of the PrintableCharStack class will respond just like the objects of the CharStack class, but they will also have the additional functionality defined in the subclass: PrintableCharStack aPrintableCharStack = new PrintableCharStack(3); |
Friday, December 7, 2007
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment