Java Reference
In-Depth Information
To see why using
final
may make for more efficient code, suppose base
class
Base
declares a final method
f
and suppose
Derived
extends
Base
. Consider
the routine
void doIt( Base obj )
{
obj.f( );
}
Since
f
is a final method, it does not matter whether
obj
actually refer-
ences a
Base
or
Derived
object; the definition of
f
is invariant, so we know
what
f
does. As a result, a compile-time decision, rather than a run-time
decision, could be made to resolve the method call. This is known as
static
binding
. Because binding is done during compilation rather than at run
time, the program should run faster. Whether this is noticeable would
depend on how many times we avoid making the run-time decision while
executing the program.
Static binding could
be used when the
method is invariant
over the inheritance
hierarchy.
A corollary to this observation is that if
f
is a trivial method, such as a sin-
gle field accessor, and is declared
final
, the compiler could replace the call to
f
with its inline definition. Thus the method call would be replaced by a single
line that accesses a data field, thereby saving time. If
f
is not declared
final
,
then this is impossible, since
obj
could be referencing a derived class object,
for which the definition of
f
could be different.
2
Static methods are not final
methods, but have no controlling object and thus are resolved at compile time
using static binding.
Static methods
have no controlling
object and thus are
resolved at com-
pile time using
static binding.
Similar to the final method is the
final class
. A final class cannot be
extended. As a result, all of its methods are automatically final methods. As an
example, the
String
class is a final class. Notice that the fact that a class has
only final methods does not imply that it is a final class. Final classes are also
known as
leaf classes
because in the inheritance hierarchy, which resembles a
tree, final classes are at the fringes, like leaves.
In the
Person
class, the trivial accessors and mutators (those starting with
get
and
set
) are good candidates for final methods, and they are declared as
such in the online code.
A
final class
may
not be extended. A
leaf class
is a final
class.
2. In the preceding two paragraphs, we say that static binding and inline optimizations “could
be” done because although compile-time decisions would appear to make sense, Section
8.4.3.3 of the language specification makes clear that inline optimizations for trivial final
methods can be done, but this optimization must be done by the virtual machine at run time,
rather than the compiler at compile time. This ensures that dependent classes do not get out
of sync as a result of the optimization.
Search WWH ::
Custom Search