Final And Inheritance Program For Java

Explain Final Keyword With Inheritance In Java, Final And Inheritance Program For Java

In This Topic & Blog Having Any Query Then Post your Comment and Suggestion Below

final Keyword with InheritanceThe 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.
System.out.println("Illegal!");
}
}
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.
180
Part I:
The Java Language


        
Chapter 8:
Inheritance
181
Using final to Prevent Inheritance
Sometimes you will want to prevent a class from being inherited. To do this, precede the
class declaration with
final
. Declaring a class as
final
implicitly declares all of its methods
as
final
, too. As you might expect, it is illegal to declare a class as both
abstract
and
final
since an abstract class is incomplete by itself and relies upon its subclasses to provide
complete implementations.
Here is an example of a
final
class:
final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}


As the comments imply, it is illegal for B to inherit A since A is declared as final.

Labels: