posted 19 years ago
Landon,
The parenthetic preceding the object on the right of the equals sign is called an "explicit cast," because you're explicitly "casting" the type of the object. Let me try to explain when this is needed...
The createScaryMonster() method is returning an object of type Monster. If you're assigning this to a variable declared as type Monster, then no cast is needed because you're handing the variable exactly what it expects. (Or more accurately, what the compiler expects for that variable.)
Monster someMonster = monsterFactory.createScaryMonster();
In fact, if you're assigning the Monster object to a variable declared as a parent class of Monster, then you still don't need an explicit cast; because upcasting (from subclass to parent) is "safe" and can be achieved automatically through "assignment conversion."
For example, suppose you had a parent class called Creature, with Monster extending Creature. Now, if your variable is expecting a Creature, and you hand it a Monster, it's still okay without an explicit cast because every Monster is a Creature.
Creature bigCreature = monsterFactory.createScaryMonster();
Note that although there is no explicit cast here, the Monster being assigned to the variable is being implicitly upcast (automatically converted) to the parent type Creature.
So when do you need an explicit cast? When you're going the other way -- when you're downcasting. If your variable is expecting a Godzilla, and you hand it a Monster, then there might be a problem because not all Monsters are Godzillas. So here you need to assure the compiler that the Monster you're assigning is, in fact, an instance of Godzilla.
Godzilla bigG = (Godzilla)monsterFactory.createScaryMonster();
Now, the explicit cast to type Godzilla will satisfy the compiler. (However, if you're wrong, and the Monster you're passing actually turns out to be a Cyclops, then you'll get a RuntimeException.)
I hope this makes sense... :roll:
[ October 15, 2004: Message edited by: marc weber ]
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org