Java Reference
In-Depth Information
Assigning an object of a derived class to a variable of a base class (or any ancestor
class) is often called upcasting because it is like a type cast to the type of the base
class. In the normal way of writing inheritance diagrams, base classes are drawn above
derived classes. 2
When you do a type cast from a base case to a derived class (or from any ancestor class
to any descendent class), it is called a downcast . Upcasting is pretty straightforward;
there are no funny cases to worry about, and in Java things always work out the way
you want them to. Downcasting is more troublesome. First of all, downcasting does
not always make sense. For example, the downcast
upcasting
downcasting
Sale saleVariable = new Sale("paint", 15);
DiscountSale discountVariable;
discountVariable = (DiscountSale)saleVariable;// Error
does not make sense because the object named by saleVariable has no instance variable
named discount and so cannot be an object of type DiscountSale . Every DiscountSale
is a Sale , but not every Sale is a DiscountSale , as indicated by this example. It is your
responsibility to use downcasting only in situations where it makes sense.
It is instructive to note that
discountVariable = (DiscountSale)saleVariable;
produces a run-time error but will compile with no error. However, the following,
which is also illegal, produces a compile-time error:
discountVariable = saleVariable;
Java catches these downcasting errors as soon as it can, which may be at compile time
or at run time, depending on the case.
Although downcasting can be dangerous, it is sometimes necessary. For example, we
inevitably use downcasting when we define an equals method for a class. For example,
note the following line from the definition of equals in the class Sale ( Display 8.1 ):
Sale otherSale = (Sale)otherObject;
This is a downcast from the type Object to the type Sale . Without this downcast, the
instance variables name and price in the return statement, reproduced as follows,
would be illegal, because the class Object has no such instance variables:
return (name.equals(otherSale.name)
&& (price == otherSale.price));
2 We prefer to think of an object of the derived class as actually having the type of its base class as well
as its own type. So this is not, strictly speaking, a type cast, but it does no harm to follow standard
usage and call it a type cast in this case.
Search WWH ::




Custom Search