Java Reference
In-Depth Information
// Create three objects of various types.
ErrorMsg myErrorMsg = new ErrorMsg ();
PopupErrorMsg myPopupMsg = new PopupErrorMsg ();
PrintfileErrorMsg myPrintMsg = new PrintfileErrorMsg ();
// Create an object of type PrintfileErrorMsg, even though its nominal
// type is ErrorMsg.
ErrorMsg myAnyMsg = new PrintfileErrorMsg ();
...
// Now, call the setErrorMsg function for each of the objects.
myErrorMsg.setErrorMsg ("Any Text");
myPopupMsg.setErrorMsg ("Any Text");
myPrintfile.setErrorMsg ("Any Text");
myAnyMsg.setErrorMsg ("Any Text");
The first two function calls perform the method
setErrorMsg
as defined in the
class
ErrorMsg
. The next two function calls will perform the method as defined in
the class
PrintfileErrorMsg
, since these objects belong to a class that has overrid-
den (i.e., defined new versions of) this method.
You may have noticed that the object type of
myAnyMsg
appears to be a little am-
biguous. Is it of type
ErrorMsg
or of type
PrintfileErrorMsg
? There are two answers
to this question. Since any derived object always contains its base class(es), one
answer is that myAnyMsg is of both types. However, since
myAnyMsg
was created using
the constructor for the class
PrintfileErrorMsg
, it is a
PrintfileErrorMsg
. And since
PrintfileErrorMsg
contains an override for the method
setErrorMsg
, the
setErrorMsg
method for this object type will be called.
P
RINTFILE
E
RROR
M
SG
C
LASS
Often, a derived class must perform the original function in the base class. In this case,
the derived class can use the operator
super
to refer to the function in the base class.
Note that the base object is not explicitly created with a
new
statement in the derived
class. Instead, it is automatically created at the same time as the derived object.
public class PrintfileErrorMsg extends ErrorMsg {
public int linesToSkip;
...
public void setErrorMsg (String inputMsg) {