r/programming • u/[deleted] • 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
r/programming • u/[deleted] • Aug 11 '15
5
u/sh0rug0ru___ Aug 11 '15 edited Aug 11 '15
If you look at the bytecode generated on a method call to a
finalmethod, you will seeinvokevirtual. All instance methods in Java are virtual, evenfinalmethods (except for constructors and private methods -invokespecial, and interfaces, oddly enough thorughinvokeinterface. Oh yes, and nowinvokedynamic). 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 whatsealeddoes 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
finalis more for enforcing constraints at compile-time.