Class Design-Subclassing In Java

0




Subclassing

In programming, you often create a model of something (for example, an employee), and then need a more specialized version of that original model. For example, you might want a model for a manager. A manager is an employee, but an employee with additional features.

Figure 1 shows the UML class diagrams that model the Employee and Manager classes.

f1

Code 1 and Code 2 show possible implementations of the Employee and Manager classes as they are modeled in Figure 1.

Code 1 A Possible Implementation of the Employee Class public class Employee {

public String name = “”;

public double salary;

public Date birthDate;

public String getDetails() {…}

}

Code 2 A Possible Implementation of the Manager Class

public class Manager {

public String name = “”;

public double salary;

public Date birthDate;

public String department;

public String getDetails() {…}

}

This example illustrates the duplication of data between the Manager clas and the Employee class. Additionally, there could be a number of methods applicable to both Employee and Manager. Therefore, you need a way to create a new class from an existing class; this is called subclassing.

In object-oriented languages, special mechanisms are provided that enable you to define a class in terms of a previously defined class. Figure 6-2 shows the UML class diagram in which the Manager class is a subclass of
the Employee class. Code 6-3 shows an implementation of the Manager class that inherits from the Employee class as modeled in Figure 6-2.

f2

Code 6-3 Another Implementation of the Manager Class

public class Manager extends Employee {

public String department;

}

Single Inheritance

The Java programming language permits a class to extend one other class only. This restriction is called single inheritance. The relative merits of single and multiple inheritance are the subject of extensive discussions among object-oriented programmers. Module 7, “Advanced Class Features,” examines a language feature called interfaces that provides most of the benefits of multiple inheritance without suffering from any of its drawbacks.




f3
The Employee class contains three attributes (name, salary, and birthDate), as well as one method (getDetails). The Manager class inherits all of these members and specifies an additional attribute, department, as well as the getDetails method. The Director class inherits all of the members of Employee and Manager and specifies a carAllowance attribute and a new method, increaseAllowance. Similarly, the Engineer and Secretary classes inherit the members of the Employee class and might specify additional members (not shown).