Java Reference
In-Depth Information
4.2.2
Explicit widening and narrowing
To cast an expression to some class, use the class name, within parentheses, as a
prefix operator. Such a cast changes the apparent type of an expression. For
example, this expression has apparent class Executive :
Activities
4-2.1, 4-2.2
new Executive("Gries", 1966, 25000)
but this expression has apparent type Employee :
(Employee) ( new Executive("Gries", 1966, 25000))
A cast (C) e is widening if C is already the apparent type of e or if C is a
superclass of the apparent type of e . A class is narrowing if C is a subclass of the
apparent type of e . Below, the cast of x is a widening cast, while the cast of y is
a narrowing cast:
Executive x= new Executive("Gries", 1966, 25000);
Employee y= (Employee) x;
Executive z= (Executive) y;
Widening casts are unnecessary because Java does them automatically.
You have to be careful with narrowing casts. You can cast an expression only
to its real type or any superclass of its real type. To see the errors you might
make, consider this expression:
a9
Employee
Employee(String, int )
getCompensation()
addToSalary( double )
toString() getName()
setName(String) getStart()
setStart( int )
name
Gries
1997
start
50,000
salary
HourlyEmployee
getHourlyPay()
getHoursWorked()
changeSalary( double d)
toString()
HourlyEmployee(String, int ,
double , int )
1600
hoursWorked
hourlyPay
15.00
PartTimeEmployee
components declared in class PartTimeEmployee
Figure 4.6:
An instance of subclass ParttimeEmployee
Search WWH ::




Custom Search