4 ms·
Methods being default virtual? Or, perhaps more accurate, being only virtual? If that's what you mean, that may well be the first time I've ever heard someone c
by cletus 6y ago
Methods being default virtual? Or, perhaps more accurate, being only virtual? If that's what you mean, that may well be the first time I've ever heard someone complain about this. I used Java for literally more than a decade and I never once thought "man I wish I could create a non-virtual function".
This seems like some C++ pattern holdover where you obviously do have virtual vs non-virtual methods. 99% of the time I suspect it's just a source of extra bugs and the vtable lookup really isn't the performance hit (most of the time) you think it is.
- pjmlp 6y agoYou can create non-virtual methods in Java, just make them final.
- cletus 6y agoOh, so the OP really means methods being non-final by default? Yeah that makes way more sense and is a valid criticism. I don't think it's that big a deal however because, in practice, libraries that use inheritance as an external API are almost an anti-pattern at this point. I forget who said it but someone (Josh Bloch? Scott Meyer?) said at one point "inheritance is an implementation detail". Or maybe it was "inheritance breaks abstraction"? Something like that anyway. I 100% agree with this. At that point it doesn't really matter if your methods are final or not. Ideally you make your leaf classes final and move on with your life. But designing for inheritance is probably not going to end well regardless other than some notable utility classes (eg AbstractMap).
- tmccrary55 6y agoAs others have mentioned in the thread, the issue is that virtual calls are more expensive because you have to resolve the correct function in the related vtable. So instead of just setting up and executing the call, you have to traipse through memory a bunch of times, affecting caches and making things slower. But the thing is, Java's compiler works at runtime, so it can either inline the function (basically dump the code into the call site instead of invoking) or devirtualize it (if the same object is called over and over, the JIT can just remember the last lookup and add a guard if the target changes). In say C++, making everything virtual would be crazy because the compiler can only safely inline in certain situations and can rarely devirtualize a call.
- ncmncm 6y agoPerformance is irrelevant to the principle involved.
- tmccrary55 6y ago!?!