We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? # to your account
在JavaGuide中提到String用final修饰是为了避免被继承后修改String的值,导致破坏String的不可变性。
实际上只需要使用private修饰byte[]数组即可保证String的不可变性,String使用final修饰的真正原因是加速String方法的调用过程。 在Java中存在着虚函数表,虚函数表的主要作用是帮助多态加速。具体来说,在编译时每个类都会生成一张虚函数表,记录着所有方法的指针。在运行时,通过实例对象的真正类型,找到虚函数表,再获得需要调用的方法的指针。这是一个动态的过程(因为需要在运行时确定方法的指针)。 而如果一个类被final修饰,那么我们在编译时即可确定对象的运行时类型(因为没有子类,自然也不用考虑多态),因此可以在编译时就确定方法指针,无需动态获取,提高了运行速度。
The text was updated successfully, but these errors were encountered:
final更是为了安全,不然来个子类覆写charAt这些方法返回一些异常值,或者toCharArray返回子类可以保留引用的数组等等问题。反例是AbstractMap.SimpleImmutableEntry因为非final所以获得此对象后返回的key value不一定final;子类可以重新实现setValue getValue。
Sorry, something went wrong.
final
https://www.baeldung-cn.com/java-final-performance#5-classes-and-methods
No branches or pull requests
在JavaGuide中提到String用final修饰是为了避免被继承后修改String的值,导致破坏String的不可变性。
实际上只需要使用private修饰byte[]数组即可保证String的不可变性,String使用final修饰的真正原因是加速String方法的调用过程。
在Java中存在着虚函数表,虚函数表的主要作用是帮助多态加速。具体来说,在编译时每个类都会生成一张虚函数表,记录着所有方法的指针。在运行时,通过实例对象的真正类型,找到虚函数表,再获得需要调用的方法的指针。这是一个动态的过程(因为需要在运行时确定方法的指针)。
而如果一个类被final修饰,那么我们在编译时即可确定对象的运行时类型(因为没有子类,自然也不用考虑多态),因此可以在编译时就确定方法指针,无需动态获取,提高了运行速度。
The text was updated successfully, but these errors were encountered: