Using final with Inheritance in java. || Use final with inheritance in java || How we use final with inheritance in java || Explain use of final with inheritance.

Using final with Inheritance in java 

1) To Prevent Overriding

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. 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.

Example

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!");
}
}


2) 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.


Example


final class A
{
// ...
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
// ...
}






Post a Comment

Please do not enter any spam link in the comment box