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

4

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

<pendantry>

All non-static methods are virtual in Java. Regardless of the pointer you have to the object (whether it is the concrete type or a super type), the same method will be called. Always.

On the other hand in C#, instance methods are by default non-virtual and cannot be overridden. But, that does not mean they cannot be overloaded. Thus, a pointer of the concrete type and a pointer of a super type can actually invoke different methods!

The equivalent to Java's final in C# is actually sealed. Which is not the default!

</pedantry>

1

u/Eirenarch Aug 11 '15

What? I am pretty sure final on a method means non-virtual in Java. final on a class means what sealed means in C#

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.