Java Reference
In-Depth Information
Figure 8.4
The output of the VirtualDemo program.
For example, when the statement executes in the VirtualDemo program, the
JVM searches down the inheritance hierarchy and discovers that Salary over-
rides mailCheck() in Employee. The JVM then invokes mailCheck() on Salary,
resulting in a virtual method invocation.
e.mailCheck();
In C++, virtual methods are not the default behavior of methods. In fact,
you must use the C++ keyword virtual to “turn on” the behavior of virtual
method invocation. The opposite is true in Java. All methods in Java are
virtual by default (virtual is not a keyword in Java), and the only way to
avoid this behavior of virtual methods is to declare a method final.
Final methods cannot be overridden, so the JVM does not need to worry
about looking down the inheritance hierarchy and trying to determine if
a child has overridden the method. For this reasons, final methods have a
performance benefit because the overhead of virtual method invocation is
avoided.
That being said, you should only declare a method as final if it is truly part
of the design of your class.
Taking Advantage of Virtual Methods
Let's look at an example where virtual methods are used to simplify and
improve the design of a Java application. In the Boss class discussed earlier, the
payEmployee() method has an Employee parameter, allowing any type of
Employee object to be passed in to the method. Within payEmployee(), we
needed to know what type of Employee was passed in so we could cast the
Employee parameter and invoke the appropriate computePay() method.
I like the Boss example because it demonstrates the instanceof keyword, an
important operator in Java that is necessary at times; however, anytime I can
Search WWH ::




Custom Search