Java Reference
In-Depth Information
public void mailCheck()
{
System.out.println(“Inside Employee mailCheck: “
+ super.toString());
System.out.println(“Mailing a check to “ + this.name + “ “
+ this.address);
}
}
In the Employee class, the super keyword is not needed to invoke
toString(). Not only is super not needed, but the call to toString()
could have used the this reference instead:
this.toString()
The toString() method can be invoked using this because Employee
inherits toString(). It can be invoked using super because toString()
is in the parent class.
The super keyword can also be used in the child class when the child wants
to invoke an overridden method in the parent. This allows the child class to
override a method when the child needs to add to the parent method, not com-
pletely change the behavior.
The following Salary class extends Employee and overrides the mailCheck()
method. Within mailCheck(), the Salary class uses super to invoke mailCheck()
in Employee.
public class Salary extends Employee
{
public float salary; //Annual salary
public float computePay()
{
System.out.println(“Computing salary pay for “ + super.name);
return salary/52;
}
public void mailCheck()
{
System.out.println(“Inside Salary mailCheck”);
super.mailCheck();
System.out.println(“Mailed check to “ + this.name
+ “ with salary “ + this.salary);
}
}
The following SuperDemo program instantiates a Salary object and invokes
the mailCheck() method. Study the program carefully and try to determine the
output, which is shown in Figure 6.4.
Search WWH ::




Custom Search