Page 518 - Introduction to Programming with Java: A Problem Solving Approach
P. 518
484 Chapter 12 Aggregation, Composition, and Inheritance
The Person class doesn’t do much. It just stores a name and allows the name to be retrieved with a getName accessor method. The Person class contains one item worth examining—the zero-parameter constructor. Normally, when a driver instantiates a Person class, the driver will assign the person’s name by passing a name argument to the one-parameter constructor. But suppose you want to test your program with a Person object, and you don’t want to hassle with storing a name in the Person object. The zero-parameter constructor allows you to do that. Do you know what name will be given to a Person object created by the zero-parameter constructor? name is a string instance variable, and the default value for a string instance variable is null. To avoid the ugly null default, note how name is initialized to the empty string.
Quick quiz: Can you achieve the same functionality by omitting the zero-parameter constructor since the compiler automatically provides a default zero-parameter constructor? Nope—remember that once you write any constructor, the compiler no longer provides a default zero-parameter constructor.
The Employee Class
Figure 12.11 contains an implementation of the derived Employee class, which provides an id. Note the extends clause in the Employee class’s heading. To enable inheritance, extends <superclass> must appear at the right of the subclass’s heading. Thus, extends Person appears at the right of the
/********************************************
*
Employee.java
Dean & Dean
The describes an employee.
*
*
*
Apago PDF Enhancer
********************************************/
public class Employee extends Person
{
private int id = 0;
//*****************************************
public Employee()
{}
public Employee(String name, int id)
{
}
// end Employee class
}
}
super(name);
this.id = id;
//*****************************************
public void display()
{
System.out.println("name: " + getName());
System.out.println("id: " + id);
This means the Employee class is derived from the Person superclass.
This calls the one-parameter Person constructor.
Since name is in a different class and is private, we must use an accessor to get it. Since getName is inherited, we don’t need a referencing prefix for it.
Figure 12.11
Employee class, derived from the Person class
⎫ ⎪ ⎪ ⎪ ⎬ ⎪ ⎪ ⎪ ⎭