Java Reference
In-Depth Information
figure 4.8
The complete
Student
and
Employee
classes,
using both forms of
super
1
class Student extends Person
2
{
3
public Student( String n, int ag, String ad, String p,
4
double g )
5
{ super( n, ag, ad, p ); gpa = g; }
6
7
public String toString( )
8
{ return super.toString( ) + getGPA( ); }
9
10
public double getGPA( )
11
{ return gpa; }
12
13
private double gpa;
14
}
15
16
class Employee extends Person
17
{
18
public Employee( String n, int ag, String ad,
19
String p, double s )
20
{ super( n, ag, ad, p ); salary = s; }
21
22
public String toString( )
23
{ return super.toString( ) + " $" + getSalary( ); }
24
25
public double getSalary( )
26
{ return salary; }
27
28
public void raise( double percentRaise )
29
{ salary *= ( 1 + percentRaise ); }
30
31
private double salary;
32
}
In the example, suppose that prior to completing the printing, we want to
give
p[3]
—which we know is an employee—a raise? Since
p[3]
is an
Employee
, it might seem that
p[3].raise( 0.04 );
would be legal. But it is not. The problem is that the static type of
p[3]
is a
Person
,
and
raise
is not defined for
Person
. At compile time, only (visible) members of
the
static type
of the reference can appear to the right of the dot operator.
We can change the static type by using a cast:
((Employee) p[3]).raise( 0.04 );
The above code makes the static type of the reference to the left of the dot
operator an
Employee
. If this is impossible (for instance,
p[3]
is in a completely
Search WWH ::
Custom Search