Java Reference
In-Depth Information
The listener reference is of type ButtonListener , but it points to a ChildListener
object. On line 8, the compiler looks for a buttonClicked method in ButtonListener and
fi nds one, so the code compiles fi le. However, at runtime, the buttonClicked method
in ChildListener is invoked. This type of behavior is referred to as virtual
method invocation , where the runtime type of an object is used to determine the
overridden method invoked at runtime, as opposed to invoking the method the compiler
found at compile time. The output of the previous statements is
Inside ChildListener
Virtual method invocation is an essential concept in Java that you must understand if you
are going to become a serious Java developer.
Casting Polymorphic References
Polymorphic references often need to be cast to their appropriate child class type. The exam
tests your knowledge of issues that arise at compile time and runtime involving the casting
of these references. In general, the only time casting is necessary is when you need to invoke
a method defi ned in a child class using a parent class or interface reference and the method
is not overridden. (If the method is overridden, invoking the parent class method causes the
child class method to execute at runtime because methods in Java are virtual.)
For example, the Cat class contains a sleep method that does not override any methods
in Pet or Mammal . To invoke sleep using a Pet reference, you need to cast the reference fi rst,
as demonstrated in the following statements:
16. Pet pet = new Cat(“Alley”, 7);
17. pet.eat(); //no cast needed
18. ((Cat) pet).sleep(); //cast is needed
19. ((Mammal) pet).breathe(); //cast is needed
20. ((Cat) pet).breathe(); //Same as previous line of code
The pet reference is of type Pet , so invoking eat on line 17 does not require a cast.
However, invoking sleep on line 18 requires pet to be cast to Cat . Invoking breathe
requires pet to be cast to either Mammal or Cat , as demonstrated on lines 19 and 20. The
output of the previous statements is
Alley is eating
Cat is sleeping
Cat is breathing
Cat is breathing
Search WWH ::




Custom Search