class声明为final的好处
來源: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怎么調用
總結
以上是生活随笔為你收集整理的class声明为final的好处的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: windows epic下载慢如何解决
- 下一篇: oracle clob 回车换行问题