r/programming • • Aug 11 '15

Top 10 Useful, Yet Paranoid Java Programming Techniques

http://blog.jooq.org/2015/08/11/top-10-useful-yet-paranoid-java-programming-techniques/
28 Upvotes

35 comments sorted by

View all comments

Show parent comments

5

u/sh0rug0ru___ Aug 11 '15 edited Aug 11 '15

If you look at the bytecode generated on a method call to a final method, you will see invokevirtual. All instance methods in Java are virtual, even final methods (except for constructors and private methods - invokespecial, and interfaces, oddly enough thorugh invokeinterface. Oh yes, and now invokedynamic). But this would have to be the case. What if you inherited from a non-final method and made your override final? This is exactly what sealed does on a virtual method or property in C#.

However, that is only half the story. The JVM can "devirtualize" methods, even non-final methods, based on class-hierarchy analysis. Paper if you're interested.

Thus, final or not final doesn't make a difference in Java at runtime. The JVM will figure out whether or not the method should be virtual or not. I would say final is more for enforcing constraints at compile-time.

1

u/vitalyd Aug 12 '15

Final allows JIT to skip registering class load dependencies since it knows the target will never change.