Java Reference
In-Depth Information
Using the references from Figure 6.5, the following statements are valid without
requiring any casting:
c.sleep();
c.breathe();
c.eat();
p.eat();
m.breathe();
Using the reference
c
, you can invoke all the methods of
Cat
,
Pet
, and
Mammal
. Using the
reference
p
, you can only invoke the
eat
method of
Pet
. Even though the corresponding
Cat
object contains
sleep
and
breathe
methods, the
p
reference does not see those methods
because the
p
reference thinks it is pointing to a
Pet
object (not a
Cat
). Similarly, using the
m
reference, you can only invoke the
breathe
method, even though the object has an
eat
and a
sleep
method. Casting is required if you want to invoke the “hidden” methods of the
Cat
object using the
m
and
p
references.
Virtual Method Invocation
Now that we have discussed polymorphism, we can discuss the concept of a
virtual
method.
All methods in Java are virtual methods, meaning that if a method is overridden,
the overridden method is always invoked at runtime, even if the compiler sees the parent
class method at compile time. For example, suppose we have the following parent class
named
ButtonListener
with a single method named
buttonClicked
:
public class ButtonListener {
public void buttonClicked() {
System.out.println(“Inside ButtonListener”);
}
}
The following
ChildListener
class extends
ButtonListener
and overrides the
buttonClicked
method:
public class ChildListener extends ButtonListener {
public void buttonClicked() {
System.out.println(“Inside ChildListener”);
}
}
Using polymorphism, the following statements are valid. Study them carefully and see if
you can determine the output:
7. ButtonListener listener = new ChildListener();
8. listener.buttonClicked();
Search WWH ::
Custom Search