Saturday, January 7, 2012

Overriding vs. Overloading

Overriding vs. Overloading

  • The subclass can override its parent class definition of fields and methods, replacing them with its own definitions and implementations.
    • To successfully override the base class method definition, the subclass method must have the same signature.
    • If the subclass defines a method with the same name as one in the base class but a different signature, the method is overloaded not overridden.
  • A subclass can explicitly invoked an ancestor class’s implementation of a method by prefixing super. to the method call. For example:
    class Subclass extends ParentClass {
        public String getDescription() {
            String parentDesc = super.getDescription();
            return "My description\n" + parentDesc;
        }
    }
Consider defining a Manager class as a subclass of Employee:
public class Manager extends Employee {
    private String responsibility;

    public Manager(String name, String ssn, String responsibility) {
        super(name, ssn);
        this.responsibility = responsibility;
    }

    public void setResponsibility(String responsibility) {
        this.responsibility = responsibility;
    }

    public String getResponsibility() {
        return this.responsibility;
    }

    public void print(String header, String footer) {
        super.print(header, null);
        System.out.println("Responsibility: " + responsibility);
        if (footer != null) {
            System.out.println(footer);
        }
    }
}
Now with code like this:
public class EmployeeDemo {
    public static void main(String[] args) {
        …
        Manager m1 = new Manager("Bob", "345-11-987", "Development");
        Employee.setBaseVacationDays(15);
        m1.setExtraVacationDays(10);
        …
        m1.print("BIG BOSS");
    }
}
The output is:
BIG BOSS
Name: Bob
SSN: 345-11-987
Email Address: null
Year Of Birth: 0
Vacation Days: 25
Responsibility: Development
Note that the Manager class must invoke one of super’s constructors in order to be a valid Employee. Also observe that we can invoke a method like setExtraVacationDays() that is defined in Employee on our Manager instance m1.

No comments: