Java Reference
In-Depth Information
overriding methods. Of course, fields that the
final
methods rely on
should be
final
or
private
, or else an extended class could change be-
havior by changing those fields.
Another ramification of
final
is that it simplifies optimizations. When a
non-
final
method is invoked, the runtime system determines the actu-
al class of the object, binds the method invocation to the correct im-
plementation of the method for that type, and then invokes that imple-
mentation. But if, for example, the
getName
method was
final
in the
Attr
class and you had a reference to an object of type
Attr
or any extended
type, it can take fewer steps to invoke the method. In the simplest case,
such as
getName
, an invocation can be replaced with the actual body of
the method. This mechanism is known as
inlining.
An inlined method
makes the following two statements perform the same:
system.out.println("id = " + rose.name);
System.out.println("id = " + rose.getName());
Although the two statements are equally efficient, a
getName
method al-
lows the
name
field to be read-only and gives you the benefits of abstrac-
tion, allowing you to change the implementation.
The same optimizations can be applied to private and static methods,
because they too cannot be overridden.
Some type checks become faster with
final
classes. In fact, many type
checks become compile time checks, and errors can be caught earlier.
If the compiler encounters a reference to a
final
class, it knows that the
object referred to is exactly that type. The entire class hierarchy for that
class is known, so the compiler can check whether any use is valid or
invalid. With a non-
final
reference, some checks can happen only at run
time.
Exercise 3.4
: Which methods (if any) of
Vehicle
and
PassengerVehicle
might reasonably be made
final
?