当前位置: 首页 > 工具软件 > ClassFinal > 使用案例 >

class声明为final的好处

田晨
2023-12-01



来源:https://zhidao.baidu.com/question/397935417.html

final class怎么调用


亲,涉及到的知识点如下:
1.final修饰类 不能被继承,也没有子类。
【使用环境】:
1.不是专门为继承而设计的类,类的本身方法之间有复杂的调用关系。假如随意创建这些类的子类,子类可能会错误的修改父类的实现细节
2.出于安全原因,类的实现细节不允许有任何改动
3.在创建对象模型的时候,确信这个类不会再被扩展
【举例】api中的java.lang.string
public final class Stringextends Objectimplements Serializable, Comparable<String>, CharSequence

来源:http://blog.csdn.net/zzxuan6/article/details/44646263

1. Virtual (overridden) methods generally are implemented via some sort of table (vtable) that is ultimately a function pointer. Each method call has the overhead of having to go through that pointer. When classes are marked final then all of the methods cannot be overridden and the use of a table is not needed anymore - this it is faster.

Some VMs (like HotSpot) may do things more intelligently and know when methods are/are not overridden and generate faster code as appropriate.

虚函数一般是通过函数表实现的,这个虚函数表其实是一个函数指针,每次函数调用都需要查询函数指针,如果一个类被标为final,那么所有的方法不会被重载,也就不需要这样的函数指针了,因而性能变得很好。�0�2现在很多虚拟机都非常智能化,以至于能够判断方法是否被重载,从而产生更快的codes。

2.The best use of final that I've seen is in library code: Making a class and/or methods final, in a library class, prevents your customers from extending it, making their code overly dependent on your implementation. Doing this enables you to make changes to your library class with confidence that they won't break client code.�0�2I'm often angry when vendors do this to me, the customer, because it prevents mocking and other good things. But I see why they do it.

可以阻止你的客户集成你实现的类,当你修改自己的库时,不用担心打牌客户的codes。

3.

3.1. Final keyword improves performance. Not just JVM can cache final variable but also application can cache frequently use final variables.�0�2

jvm能够缓存final变量,应用程序也能够缓存频繁使用的final变量
3.2. Final variables are safe to share in multi-threading environment without additional synchronization overhead.�0�2
final变量能够在多线程环境下安全使用
3.3. Final keyword allows JVM to optimized method, variable or class.
final变量容许JVM优化方法、变量和类
4. As you see there are a lot of JIT compilers in the world and mainly you don't know which one will be used to execute (and optimize) your Java program on the fly, so you should keep in mind that methods of final classes can be used by JIT more optimally because it can address them directly since their methods can't be overridden by successors and JIT can make some economy to avoid virtual tables usage. I repeat that it depends on used JIT.
世界上有很多种JIT编译器,你不知道你的java程序到底使用哪种编译器编译,但是你如果将编译器设计为 final的,jit能够避免使用虚函数表从而更加经济。

you can define final class when you need to create a class to connect to a data base or to a XML

final class怎么调用

 类似资料: