Java Reference
In-Depth Information
This makes sense, because you want code written for the base class method to work
for the derived class method. You can use a public method anyplace that you can use a
private method, but it is not true that you can use a private method anyplace that you
can use a public method.
PITFALL: Overriding versus Overloading
Do not confuse overriding (that is, redefining) a method definition in a derived class
with overloading a method name. When you override a method definition, the new
method definition given in the derived class has the exact same number and types
of parameters. On the other hand, if the method in the derived class were to have a
different number of parameters or a parameter of a different type from the method
in the base class, then the derived class would have both methods. That would be
overloading. For example, suppose we add the following method to the definition of
the class HourlyEmployee ( Display 7.3 ):
public void setName(String firstName, String lastName)
{
if ( (firstName == null ) || (lastName == null ) )
{
System.out.println("Fatal Error setting employee name.");
System.exit(0);
}
else
name = firstName + " " + lastName;
}
The class HourlyEmployee would then have this two-argument method setName ,
and it would also inherit the following one-argument method setName from the base
class Employee :
public void setName(String newName)
{
if (newName == null )
{
System.out.println("Fatal Error setting employee name.");
System.exit(0);
}
else
name = newName;
}
The class HourlyEmployee would have two methods named setName . This would
be overloading the method name setName .
(continued)
 
Search WWH ::




Custom Search