Why final classes cannot be overridden in java?
我被问到为什么最后一个类不能被重写的原因。我试着解释,它更多的是一种设计方法,在这种方法中,您不希望类被扩展或方法被重写,而最终类也有助于使对象不可变(尽管还有更多的步骤要做,而不仅仅是将类声明为最终类)。
但是,我想知道在声明类为final之后是否还有更多的思考过程,或者不能重写它的事实?
因为它们是规则;它是语言设计的一部分。
http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html jls-8.1.1.2
作为一个设计器,你说"我的类不适合继承";Java通过明确阻止某人这样做来荣耀这个。
最后一个类是不能扩展的类,这就是U不能重写最后一个类的原因。
它还用于使类不可变
将类定义为最终类的一个很好的优点是它提高了JVM性能看看这个
因为Java编译器遵循Java语言规范所定义的不允许的规则,所以不能扩展最终类,因为Java编译器不允许它。
来自wiki
A final method cannot be overridden or hidden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.
A common misconception is that declaring a class or method as final improves efficiency by allowing the compiler to directly insert the method wherever it is called (see inline expansion). But because the method is loaded at runtime, compilers are unable to do this. Only the runtime environment and JIT compiler know exactly which classes have been loaded, and so only they are able to make decisions about when to inline, whether or not the method is final.
号