1. V irtual (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,那麼所有的方法不會被重載,也就不需要這樣的函數指針了,因而性能變得很好。 現在很多虛拟機都非常智能化,以至于能夠判斷方法是否被重載,進而産生更快的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. I'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.
jvm能夠緩存final變量,應用程式也能夠緩存頻繁使用的final變量
3.2. Final variables are safe to share in multi-threading environment without additional synchronization overhead.
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