Java Reference
In-Depth Information
This is true in the reverse, so you can use a superclass when a subclass is expected.
There is a catch, however: Because subclasses contain more behavior than their super-
classes, there's a loss in precision involved. Those superclass objects might not have all
the behavior needed to act in place of a subclass object. For example, if you have an
operation that calls methods in objects of the class Integer , using an object of class
Number won't include many methods specified in Integer . Errors occur if you try to call
methods that the destination object doesn't have.
To use superclass objects where subclass objects are expected, you must cast them
explicitly. You won't lose any information in the cast, but you gain all the methods and
variables that the subclass defines. To cast an object to another class, you use the same
operation as for primitive types:
( classname ) object
In this case, classname is the name of the destination class, and object is a reference to
the source object. Note that casting creates a reference to the old object of the type
classname ; the old object continues to exist as it did before.
3
The following example casts an instance of the class VicePresident to an instance of
the class Employee ; VicePresident is a subclass of Employee with more information:
Employee emp = new Employee();
VicePresident veep = new VicePresident();
emp = veep; // no cast needed for upward use
veep = (VicePresident)emp; // must cast explicitly
As you'll see when you begin working with graphical user interfaces during Week 2,
“The Java Class Library,” casting one object is necessary whenever you use Java2D
graphics operations. You must cast a Graphics object to a Graphics2D object before you
can draw onscreen. The following example uses a Graphics object called screen to cre-
ate a new Graphics2D object called screen2D :
Graphics2D screen2D = (Graphics2D)screen;
Graphics2D is a subclass of Graphics , and both are in the java.awt package. You
explore the subject fully during Day 13, “Using Color, Fonts, and Graphics.”
In addition to casting objects to classes, you also can cast objects to interfaces, but only
if an object's class or one of its superclasses actually implements the interface. Casting
an object to an interface means that you can call one of that interface's methods even if
that object's class does not actually implement that interface.
Search WWH ::




Custom Search