Final (Java): Difference between revisions

Content deleted Content added
== See also == * final (C++), as article has now been restored
marking dead link
Line 17:
==Final methods==
 
A final [[Method (computer science)|method]] cannot be [[Method overriding|overridden]] or hidden by subclasses.<ref>[http{{Cite web |title=Chapter 8. Classes |url=https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls |access-8.4.3.3date=2024-04-25 JLS 8|website=docs.4oracle.3.3. final Methods]com}}</ref> This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.<ref>[http://java.sun.com/docs/books/tutorial/java/IandI/final.html Writing Final Classes and Methods]</ref>
 
Example:
Line 40:
</syntaxhighlight>
 
A common misconception is that declaring a method as <code>final</code> improves efficiency by allowing the compiler to directly insert the method wherever it is called (see [[inline expansion]]). Because the method is loaded at [[run time (program lifecycle phase)|runtime]], compilers are unable to do this. Only the runtime environment and [[Just-in-time compilation|JIT]] compiler know exactly which classes have been loaded, and so only they are able to make decisions about when to inline, whether or not the method is final.<ref>[http{{Cite web |title=IBM Developer |url=https://wwwdeveloper.ibm.com/developerworkslanguages/java/library/j |url-jtp1029.htmlstatus=dead Java theory and|access-date=2024-04-25 practice: Is that your final answer?]|website=developer.ibm.com}}</ref>
 
Machine code compilers that generate directly executable, platform-specific [[machine code]], are an exception. When using [[static linking]], the compiler can safely assume that methods and variables computable at [[compile-time]] may be inlined.