(^350) | Inheritance, Polymorphism, and Scope
The constructor can call its superclass constructor and then store the extension.
knowExtensionjust returns the value of extension.asDigitsand asStringcan call upon their su-
perclass methods to help them.
packagephone;
public classBusinessPhone extendsPhone
// Adds an extension to an object of class Phone
{
private intextension;
publicBusinessPhone(int area, int number, int exten)
{
super(area, number); // Calls superclass constructor
extension = exten;
}
// Knowledge methods
public intknowExtension()
{
returnextension;
}
public longasDigits()
{
longdigits;
digits = super.asDigits(); // Accesses superclass method
return(long) (digits 10000 + extension);
}
publicString asString()
{
String string = super.asString(); // Accesses superclass method
return(string + "-" + extension);
}
}
Notice that the asDigitsand asStringmethods of BusinessPhoneoverride the instance
methods of the same name in Phone. The new class inherits all of the fields and methods of
Phoneand then adds some of its own. The following program is a test driver that creates a Phone
object and three BusinessPhoneobjects, and applies the methods from both classes to them:
importjava.io.;
importphone.*;
public classTestDrPhone
T
E
A
M
F
L
Y
Team-Fly®
やまだぃちぅ
(やまだぃちぅ)
#1