我正在读一本关于Java的书,它说你可以将整个类声明为final。我想不出有什么地方可以用它。

我只是一个编程新手,我想知道程序员是否真的在他们的程序中使用这个。如果他们使用,他们什么时候使用,这样我就能更好地理解它,知道什么时候使用它。

如果Java是面向对象的,并且你声明了一个final类,难道它不会阻止类具有对象的特征吗?


当前回答

Be careful when you make a class "final". Because if you want to write an unit test for a final class, you cannot subclass this final class in order to use the dependency-breaking technique "Subclass and Override Method" described in Michael C. Feathers' book "Working Effectively with Legacy Code". In this book, Feathers said, "Seriously, it is easy to believe that sealed and final are a wrong-headed mistake, that they should never have been added to programming languages. But the real fault lies with us. When we depend directly on libraries that are out of our control, we are just asking for trouble."

其他回答

相关阅读:Bob Martin的《开闭原理》。

主要引用:

软件实体(类、模块、 函数等)应该是开放的 分机,但已关闭 修改。

最后一个关键字是在Java中强制执行的方法,无论是在方法上还是在类上。

在一个场景中,final很重要,当您出于安全原因想要防止类的继承时。这允许您确保您正在运行的代码不会被其他人覆盖。

另一个场景是为了优化:我似乎记得Java编译器内联了final类中的一些函数调用。因此,如果你调用a.x()并且a被声明为final,我们在编译时就知道代码将是什么,并且可以内联到调用函数中。我不知道这是否真的做到了,但最终是有可能的。

在java中,final关键字用于以下场合。

最后一个变量 最后的方法 最后的课程

在java中,final变量不能重赋,final类不能扩展,final方法不能重写。

其他的答案集中在final类告诉编译器什么:不允许另一个类声明它扩展了这个类,以及为什么这样做是可取的。

但是编译器并不是短语final类的唯一读者。每个读源代码的程序员也会读这个。它可以帮助快速理解程序。

In general, if a programmer sees Thing thing = that.someMethod(...); and the programmer wants to understand the subsequent behaviour of the object accessed through the thing object-reference, the programmer must consider the Thing class hierarchy: potentially many types, scattered over many packages. But if the programmer knows, or reads, final class Thing, they instantly know that they do not need to search for and study so many Java files, because there are no derived classes: they need study only Thing.java and, perhaps, it's base classes.

Final类不能扩展。因此,如果你想要一个类以某种方式运行,并且不希望有人重写方法(可能效率较低,恶意代码更多),你可以将整个类声明为final或你不想被更改的特定方法。

由于声明一个类并不会阻止一个类被实例化,这并不意味着它会阻止类具有对象的特征。只是您必须坚持使用类中声明方法的方式。