Consider the following definition:
class Employee { private String name; private double salary; // Constructors public Employee(String n, double s){ name = n; salary = s; } public Employee(String n){ this(n,500.00); } // "mutator" methods public boolean setName(String s){ ... } public boolean setSalary(double x){ ... } // "accessor" methods public String getName(){ ... } public double getSalary(){ ... } // other methods double bonus(float percent){ return (percent/100.0)*salary; } }
Suppose we want to define a class of Managers, who are like Employees except that they have, in addition, a secretary. We can ``re-use'' the Employee class as follows:
class Manager extends Employee { private String secretary; public boolean setSecretary(name s){ ... } public String getSecretary(){ ... } }
Objects of type Manager implicitly inherit instance variables and methods from Employee. Thus, every Manager object has a name and salary in addition to a secretary.
In OO terminology, Manager is referred to as the subclass while Employee is referred to as the superclass. In general, a subclass specializes the superclass. The terminology makes sense set-theoretically: every Manager is also an Employee so the set of Managers is a subset of the set of Employees.
The class Manager cannot see the private fields of Employee! This is to prevent the data encapsulation from being broken--often the programmer who creates a subclass is not the one who wrote the parent class. A constructor for Manager must call Employee constructor to set name and salary. In a hierarchy of classes, this transfers the responsibility for construction of higher levels to the parent class, which inductively ``knows what to do''. We use the word super to call the parent constructor. Thus, we would write:
// Constructors public Manager(String n, double s, String sn){ super(n,s); // "super" calls the Employee constructor secretary = sn; }
Manager can override a method from Employee. For instance, Manager may redefine bonus as follows--note the use of super to unambiguously use the superclass's bonus in this definition.
double bonus(float percent){ return 1.5*super.bonus(percent); }
In general, the subclass has greater functionality (more fields and methods) than the superclass. So, casting ``up'' the hierarchy is permitted. For example,
Employee e = new Manager ( ....)
A Manager object can do everything that an Employee object can. The converse is not possible. What would the reference to getSecretary() mean in the following code?
Manager m = new Employee(...); System.out.println(m.getSecretary());