Java Reference
In-Depth Information
location 2000
superCat = 2000
fictionalCat = 2000
name = Bob
goodpower = 10
respect = 10
super object
FIGURE 8.5: Autocasting.
Enter your choice:
Name: Joker
Evil Power[1-10]:
1. Enter Superhero
2. Enter Villain
3. Finish Entering
Enter your choice: 3
Superman is a superhero that has good power = 8 and respect = 8
Joker is a villain that has evil power = 7 and narcissism = 10
Few magical things happened while the program was executing. First, note that we
were able to insert both superheroes and villains in the ArrayList . The reason is that
the ArrayList was defined to contain objects of type FictionalCharacter . Since both
superheroes and villains are fictional characters, Java automatically converts them to fic-
tional characters. In other words, in an ArrayList<FictionalCharacter> we can store
any object that is of type FictionalCharacter or that belongs to a subclass of the
FictionalCharacter class.
Here is a simple example to clarify things.
Superhero superCat = new Superhero( "Bob" ,10,10) ;
FictionalCharacter fictionalCat = superCat;
Figure 8.5 explains the design. We have two pointers to the same object. Note that the
type of the fictionalCat object is FictionalCharacter , but it references a Superhero .
Java automatically casts the superCat object to an object of type FictionalCharacter .
Note that the code can also be rewritten as follows.
Superhero superCat = new Superhero( "Bob" ,10,10) ;
FictionalCharacter fictionalCat = (FictionalCharacter)superCat;
However, the cast is not required.
Search WWH ::

Custom Search