Java Reference
In-Depth Information
C
ALLER
C
LASS
Using this interface technique, the class
PrintfileErrorMsg
can now receive a re-
quest to print the error message using the
printLine
method. At the same time,
PrintfileErrorMsg
can also support the methods in the base class
ErrorMsg
(such as
setErrorMsg
):
// Create an instance of a PrintfileErrorMsg.
PrintfileErrorMsg myPrintMsg = new PrintfileErrorMsg ();
// Call the derived method in PrintfileErrorMsg.
myPrintMsg.setErrorMsg ("Any Text");
// Call the interface method in PrintfileErrorMsg.
myPrintMsg.printLine();
One key difference between these two method implementations is that the class
PrintfileErrorMsg
can
override the
setErrorMsg
method, but if it does not, the
method in the base class (
ErrorMsg
) will be executed. However, in order to receive a re-
quest to print its error message (the
printLine
method),
PrintfileErrorMsg
must
im-
plement this method, since there is no real base class method that can be performed.
U
SING
I
NTERFACES
Interfaces are often supported by helper classes that perform the basic functions of
that interface. These supporting classes provide basic implementations of the de-
fined interface. A class that implements a particular interface can simply use these
supporting classes as is or implement additional features in addition to the basic
features provided.
public class WriteLineImpl {
// This class provides the implementation defined in the WriteLine
// Interface.
public void printLine (String inputMsg) {
System.out.println (inputMsg);
}
}
// PrintfileErrorMsg will use the helper class WriteLineImpl to
// implement the method defined in the WriteLine Interface.
public class PrintfileErrorMsg extends ErrorMsg
implements Writeline {