Page 566 - Introduction to Programming with Java: A Problem Solving Approach
P. 566

                532 Chapter 13 Inheritance and Polymorphism
definitions of the getPay method in all of the Employee2 descendant classes? Yes, the Salaried and Hourly classes in Figures 13.11 and 13.12 already contain the required getPay method definitions. How- ever, we need to revise the Salaried, Hourly, and Payroll classes by making these replacements:
Employee → Employee2 Salaried → Salaried2 Hourly → Hourly2 Payroll → Payroll2
Then the Salaried2, Hourly2, and Payroll2 classes will start out looking like this: public class Salaried2 extends Employee2
{
...
public class Hourly2 extends Employee2
{
...
public class Payroll2
{
public static void main(String[] args)
{
            Apago PDF Enhancer
Here’s another thing to note when declaring an abstract method. Since an abstract method dec- laration does not provide a definition for that method, the class definition is incomplete. Since the class definition is incomplete, it can’t be used to construct objects. The compiler recognizes this and complains if you don’t recognize it in your code. To satisfy the compiler, you must add an abstract modifier to the class heading whenever you have a class that contains one or more abstract methods. For example, note the abstract modifier in the Employee2 class heading in Figure 13.13.
Adding an abstract modifier to a class heading makes it impossible to instantiate an object from that class. If a program attempts to instantiate an abstract class, the compiler generates an error. For example, since Employee2 is an abstract class, we’d get a compilation error if we had a main method like this:
Employee2[] employees = new Employee2[100];
...
public static void main(String[] args)
     {
  }
Employee2 emp = new Employee2("Benji");
Sometimes you don’t want a child class to define a method that was declared to be abstract in its parent. Instead you want to defer the method definition to the next generation. It’s easy to do this. In the child class, just ignore that method and declare the child class abstract also (since at least that method is still undefined). You can defer method definitions like this as far as you want, provided you ultimately define them all in any non-abstract descendant class you use to instantiate objects.
We have said that if any method in a class is abstract, that class must be abstract. But this does not mean all methods in an abstract class must be abstract. It’s frequently useful to include
B
e
c
B
ec
a
bs
s
t
a
u
tr
u
s
ra
s
e
ac
eE
i
th
h
i
is
s
g
g
e
en
n
e
e
r
ra
i
s
 E
m
s
mp
p
l
lo
oy
ye
ee
e2
2
 t,
,t
a
t
te
es
 a
s
ab
a
ac
c
o
om
mp
p
i
il
c
t
 la
a
t
t
i
i
o
o
n
n
e
e
r
rr
ro
or
r
.
.
   564   565   566   567   568