7 Using Final With Inheritance
7 Using Final With Inheritance
OOC
4th Sem, ‘B’ Div
2016-17
Prof. Mouna M. Naravani
➢ The keyword final has three uses.
➢ variable
➢ method
➢ class
1. Java final variable
➢ It can be used to create the equivalent of a named constant.
➢ Doing so prevents its contents from being modified.
➢ This means that you must initialize a final variable when it is declared.
➢ If you make any variable as final, you cannot change the value of final variable(It will be
constant).
➢ Ex: final int max = 50;
2) Java final method (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.
➢ If you make any method as final, you cannot override it.
class A {
final void method1()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void method1() { // Compile Time ERROR! Can't override.
System.out.println("Illegal!");
}
}
There are two types of binding
➢ Static binding (also known as early binding) – At Compile Time
➢ Dynamic binding (also known as late binding) – At Run Time
3) Java final class (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.
final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
It is illegal for B to inherit A since A is declared as final.
}
Difference between abstract and final
abstract final
Abstract class object cannot be created. Final class object can be created.
References