Java Reference
In-Depth Information
Although you cannot cast between unrelated objects, from Spaniel to Duck for example, you can achieve
a conversion by writing a suitable constructor, but obviously only where it makes sense to do so. You just
write a constructor in the class to which you want to convert and make it accept an object of the class you
are converting from as an argument. If you really thought Spaniel to Duck was a reasonable conversion,
you could add the constructor to the Duck class:
public Duck(Spaniel aSpaniel) {
// Back legs off, and staple on a beak of your choice...
super("Duck"); // Call the base constructor
name = aSpaniel.getName();
breed = "Barking Coot"; // Set the duck breed for a converted Spaniel
}
This uses the getName() method in the Dog class that is inherited in the class Spaniel , and which returns
the value of name for an object. This constructor accepts a Spaniel and turns out a Duck . This is quite dif-
ferent from a cast though. This creates a completely new object that is separate from the original, whereas a
cast presents the same object as a different type.
When to Cast Objects
You will have cause to cast objects in both directions through a class hierarchy. For example, whenever you
execute methods polymorphically, you are storing objects in a variable of a base class type and calling meth-
ods in a derived class. This generally involves casting the derived class objects to the base class. Another
reason you might want to cast up through a hierarchy is to pass an object of several possible subclasses to
a method. By specifying a parameter as a base class type, you have the flexibility to pass an object of any
derived class to it. You could pass a Dog , Duck , or Cat object to a method as an argument for a parameter of
type Animal , for example.
The reason you might want to cast down through a class hierarchy is to execute a method unique to a
particular class. If the Duck class has a method layEgg() , for example, you can't call this using a variable of
type Animal , even though it references a Duck object. As I said, casting downward through a class hierarchy
always requires an explicit cast.
TRY IT OUT: Casting Down to Lay an Egg
Let's amend the Duck class and use it along with the Animal class in an example. Add layEgg() to the
Duck class as:
public class Duck extends Animal {
public void layEgg() {
System.out.println("Egg laid");
}
// Rest of the class as before...
Search WWH ::




Custom Search