我正在读一本关于Java的书,它说你可以将整个类声明为final。我想不出有什么地方可以用它。
我只是一个编程新手,我想知道程序员是否真的在他们的程序中使用这个。如果他们使用,他们什么时候使用,这样我就能更好地理解它,知道什么时候使用它。
如果Java是面向对象的,并且你声明了一个final类,难道它不会阻止类具有对象的特征吗?
我正在读一本关于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."
其他回答
是的,有时您可能需要这样做,无论是出于安全性还是速度原因。在c++中也可以做到。它可能不适用于程序,但更适用于框架。 http://www.glenmccl.com/perfj_025.htm
如果类被标记为final,这意味着类的结构不能被任何外部的东西修改。最明显的是当你在做传统的多态继承时,基本上类B扩展A是行不通的。它基本上是一种保护代码某些部分(一定程度上)的方法。
澄清一下,标记类final并没有将其字段标记为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."
在一个场景中,final很重要,当您出于安全原因想要防止类的继承时。这允许您确保您正在运行的代码不会被其他人覆盖。
另一个场景是为了优化:我似乎记得Java编译器内联了final类中的一些函数调用。因此,如果你调用a.x()并且a被声明为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.