What is the point of "final class" in Java?
One scenario where final is important, when you want to prevent inheritance of a class, for security reasons. This allows you to make sure that code you are running cannot be overridden by someone.
Another scenario is for optimization: I seem to remember that the Java compiler inlines some function calls from final classes. So, if you call a.x()
and a is declared final
, we know at compile-time what the code will be and can inline into the calling function. I have no idea whether this is actually done, but with final it is a possibility.
The best example is
public final class String
which is an immutable class and cannot be extended. Of course, there is more than just making the class final to be immutable.
First of all, I recommend this article: Java: When to create a final class
If they do, when do they use it so I can understand it better and know when to use it.
A final
class is simply a class that can't be extended.
(It does not mean that all references to objects of the class would act as if they were declared as final
.)
When it's useful to declare a class as final is covered in the answers of this question:
- Good reasons to prohibit inheritance in Java?
If Java is object oriented, and you declare a class
final
, doesn't it stop the idea of class having the characteristics of objects?
In some sense yes.
By marking a class as final you disable a powerful and flexible feature of the language for that part of the code. Some classes however, should not (and in certain cases can not) be designed to take subclassing into account in a good way. In these cases it makes sense to mark the class as final, even though it limits OOP. (Remember however that a final class can still extend another non-final class.)
In Java, items with the final
modifier cannot be changed!
This includes final classes, final variables, and final methods:
- A final class cannot be extended by any other class
- A final variable cannot be reassigned another value
- A final method cannot be overridden