Final Classes and Methods


Inheritance is surely one of the highly useful features in Java. But at times, it may be desired that a class should not be extendable by other classes to prevent exploitation. For such purpose, we have the final keyword. We have already seen even what final variables are. Final classes and methods are also similar. A class declared as final cannot be extended while a method declared as final cannot be overridden in its subclasses. A method or a class is declared to be final using the final keyword. Though a final class cannot be extended, it can extend other classes. In simpler words, a final class can be a sub class but not a super class.
final public class A {
//code
}
The final keyword can be placed either before or after the access specifier. The following declaration of class A is equivalent to the above.
public final class A {
//code
}
To make it more clear, there should be no specifiers between a class name and the keyword class. All other specifiers may be placed to the left of the keyword class in any order.
Final methods are also declared in a similar way. Here too, there should be no specifiers stated between the return type and the method name. For example, to make a static method declared with the public access specifier final, the three specifiers, public, static and final may be placed in any order to the left of the return type.
public final void someMethod() {
//code
}
When we attempt to extend a final class or override a final method, compilation errors occur.
class B extends A { // compilation error, A is final
}
We will now look into a small trivial example to understand the necessity of final classes and methods. Consider that you are a developer writing classes for use by others. You have two classes named Car and Vehicle defined in the following way and of course with may other methods of your own.
public class Car {

Public void move() {
System.out.println(“Moving on road”);
}
}

Class MoveAVehicle {

Public static void move(Car c) {
c.move();
}
}

Now, since the class Car is not final, other people may extend it to their own classes. Following is an example:
class Aeroplane extends Car {

Public void move() {
System.out.println(“Moving in air”);
}
}

This is logically wrong. An aeroplane is definitely not a Car. And a statement like the following would print absurd data on the screen.
MoveAVehicle( new Aeroplane() );
In order to avoid such illogical extending of classes; classes and methods may be marked as final. The example cited above is just illustrative. The actual scenario in real world programming is much more complex.
Author: , 0000-00-00