Use of final class in Java
I am reading a book about Java and it says that you can declare the whole class as final
. I cannot think of anything where I'd use this.
I am just new to programming and I am wondering if programmers actually use this on their programs . If they do, when do they use it so I can understand it better and know when to use it.
If Java is object oriented, and you declare a class final
, doesn't it stop the idea of class having the characteristics of objects?
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 .
(This 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:
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.)
Related article: Java: When to create a final class
In Java, items with the final
modifier cannot be changed!
This includes final classes, final variables, and final methods:
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 ax()
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.
上一篇: 如何使用多个初始化参数创建自定义异常类pickleable
下一篇: 在Java中使用final类