Inheritance is one of the OOP’s important principles. The other two are Encapsulation and Polymorphism. The
important topics to study in Inheritance are extending one to class to other,
order of constructor calling, super keyword usage, method overriding and
dynamic method dispatch. Understanding these topics thoroughly is important for
java beginners. If you want to take a free tutorial on these topics
then visit my blog’s tutorial pages: Inheritance Basics and Method Overridingin Java.
All these above mentioned concepts
will help you to implement Inheritance principle while writing the java
program. But what if you want to prevent
Inheritance i.e. want your classes to be prevented from being inherited. What if you
have a requirement, when you are developing an application using Java that you
need to prevent overriding of some methods?
The answer for both the questions in
one and the same, yes! You just have to use final keyword of Java. The implementation is illustrated below with
few code fragments.
- Using final keyword to prevent Inheritance:
You can see the code fragment below
where final keyword is used before
the keyword class in implementing a class called X. This use of final keyword
prevents the class X from being inherited by the other classes. If any class tries
to inherit class X an error will result during compilation. You can see class Y
trying to inherit the class X is resulting in an error.
final class X //
final class cannot be inherited
{
//body of class
}
class Y extends X // Error!! Illegal you can’t inherit a final class. X is
final class
{
//body of class
}
- Using final keyword to prevent method overriding:
In the below code fragment you can
see final keyword is specified
before the type signature of method noOvRide(). This will prevent the method
noOvRide() from overding by the other classes. In the code fragment
illustration below you can see class Y is trying to override a final method noOvRide() present in its superclass X. Doing so will
result in an error during compilation.
class X //
final class cannot be inherited
{
//…..
final void noOvRide() //final method, can’t override
{
//body of method
}
}
class Y extends X
{
//…..
void noOvRide() // Error!!
{
//illegal not possible to override the
method because its’ final
}
}
Recommended Java Books for Java Beginners: