How to Typecast in Java 6
In computer programming, typecasting refers to taking an object of one type and converting it into an object of another type. In Java 6, this usually, but not always, involves either upcasting or downcasting, which means to cast an object up or down the inheritance hierarchy.
Instructions
-
-
1
Paste the following Java classes into a blank text file. These are the class that will be used for the tutorial:
public class Person { }
public class MalePerson extends Person { }
-
2
Paste the following upcast:
Person p = new MalePerson("Tom");
The MalePerson class is a subclass of Person, so this is a cast up the hierarchy. Upcasting is the easiest type of cast to pull off. Java simply knows what to do when a subclass is assigned to one of its ancestors. Make a mental note, however: Java will always remember what an object really is during an upcast. Even now that the MalePerson "Tom" has been assigned to a generic person object, Java remembers that this object is really a MalePerson.
-
-
3
Paste the following downcast:
Person p = new MalePerson("Tom");
MalePerson m = (MalePerson) p;
Downcasts like this, that move down the hierarchy, require the programmer to specify the class type being used for the cast in parenthesis. However, downcasting is more complex than upcasting.
-
4
Attempt the following downcast:
Person p = new Person("Jane");
MalePerson m = (MalePerson) p;
This attempt fails, and it shouldn't be hard to see why. While it is reasonable to assume that a MalePerson is a Person, it is not reasonable for the computer to assume that all Persons are MalePersons. A few may be FemalePersons, and the difference may or may not be trivial for the computer's purposes. Just to be safe, the program throws an error.
A downcast can only occur if an upcast has occurred first, which is why the upcast in Step 3 was valid, but not in Step 4. This may make upcasting sound useless at first. It begs the question of why the upcast was performed in the first place, but hold that thought.
-
5
Consider the following method:
public void greet(Person p) {
if (p instanceof MalePerson) {
MalePerson m = (MalePerson) p;
m.doMaleThings();
} else if (p instanceof FemalePerson) {
FemalePerson f = (MalePerson) p;
f.doFemaleThings();
} else throw new GenderConfusionException();
}
The writer of this method has no way of knowing in advance whether this method will be called with a MalePerson or a FemalePerson object, so he uses the generic Person object. Then, he uses the instanceof command to poll the Person given and see whether he should downcast it as a male or a female person.
-
1