5.2 Overriding methods |
For instance here is the definition for the Employee class from the previous section:
public class Employee extends Person { public String employeeID; public Date startDate; public int leaveTaken; public int sickDaysTaken; public int calculateLeave() { //... leave calculation goes here } }The company could now start hiring casual staff. These staff members get no annual leave. To implement this business rule the following class could be created:
public class CasualEmployee extends Employee { public int calculateLeave() { return 0; } }The CasualEmployee class extends the Employee class. This means that it inherits all the attributes and methods that the Employee class has. The CasualEmployee class however overrides the calculateLeave() method, forcing it to return 0.
So calling calculateLeave() on an Employee object will trigger the original code, while calling calculateLeave() on a CasualEmployee will call the new code that always returns 0.
In an overriding method the overridden method can be accessed by calling the overridden method on the super identifier. The super identifier refers to the super class of the class.
For instance in calculateLeave() method on the CasualEmployee class you could code the following to call the calculateLeave() method on the Employee class:
int normalLeave = super.calculateLeave(); // call super class's caculateLeave() method