Java Reference
In-Depth Information
objects. The program will iterate through the array and call method earnings for each
Employee object. Java processes these method calls polymorphically . Declaring earnings as
an abstract method in Employee enables the calls to earnings through Employee variables
to compile and forces every direct concrete subclass of Employee to override earnings .
Method toString in class Employee returns a String containing the first name, last
name and social security number of the employee. As we'll see, each subclass of Employee
overrides method toString to create a String representation of an object of that class that
contains the employee's type (e.g., "salaried employee:" ) followed by the rest of the
employee's information.
Let's consider class Employee 's declaration (Fig. 10.4). The class includes a con-
structor that receives the first name, last name and social security number (lines 11-17);
get methods that return the first name, last name and social security number (lines 20-23,
26-29 and 32-35, respectively); method toString (lines 38-43), which returns the
String representation of an Employee ; and abstract method earnings (line 46), which
will be implemented by each of the concrete subclasses. The Employee constructor does not
validate its parameters in this example; normally, such validation should be provided.
1
// Fig. 10.4: Employee.java
2
// Employee abstract superclass.
3
4
public abstract class Employee
5
{
6
private final String firstName;
7
private final String lastName;
8
private final String socialSecurityNumber;
9
10
// constructor
11
public Employee(String firstName, String lastName,
12
String socialSecurityNumber)
13
{
14
this. firstName = firstName;
15
this. lastName = lastName;
16
this. socialSecurityNumber = socialSecurityNumber;
17
}
18
19
// return first name
20
public String getFirstName()
21
{
22
return firstName;
23
}
24
25
// return last name
26
public String getLastName()
27
{
28
return lastName;
29
}
30
31
// return social security number
32
public String getSocialSecurityNumber()
33
{
Fig. 10.4 | Employee abstract superclass. (Part 1 of 2.)
 
Search WWH ::




Custom Search