figref = t;
System.out.println("Area is " + figref.area());
As the comment inside main( ) indicates, it is no longer possible to declare objects of
type Figure, since it is now abstract. And, all subclasses of Figure must override area( ). To
prove this to yourself, try creating a subclass that does not override area( ). You will receive
a compile-time error.
Although it is not possible to create an object of type Figure, you can create a reference
variable of type Figure. The variable figref is declared as a reference to Figure, which means
that it can be used to refer to an object of any class derived from Figure. As explained, it is
through superclass reference variables that overridden methods are resolved at run time.
Using final with Inheritance
The keyword final has three uses. First, it can be used to create the equivalent of a named
constant. This use was described in the preceding chapter. The other two uses of final apply
to inheritance. Both are examined here.
Using final to Prevent Overriding
While method overriding is one of Java's most powerful features, there will be times when
you will want to prevent it from occurring. To disallow a method from being overridden,
specify final as a modifier at the start of its declaration. Methods declared as final cannot
be overridden. The following fragment illustrates final:
class A {
final void meth() {
System.out.println("This is a final method.");
class B extends A {
void meth() { // ERROR! Can't override.
Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do
so, a compile-time error will result.
Methods declared as final can sometimes provide a performance enhancement: The
compiler is free to inline calls to them because it "knows" they will not be overridden
by a subclass. When a small final method is called, often the Java compiler can copy the
bytecode for the subroutine directly inline with the compiled code of the calling method,
thus eliminating the costly overhead associated with a method call. Inlining is only an
option with final methods. Normally, Java resolves calls to methods dynamically, at run
time. This is called late binding. However, since final methods cannot be overridden, a call
to one can be resolved at compile time. This is called early binding.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks