Final (Java): Difference between revisions

Content deleted Content added
Shagie (talk | contribs)
Final variables: Make sentence agree with reference, make code example agree with sentence.
Final methods: clarifying effect of "final" on static methods
Line 17:
== Final methods ==
 
A '''final [[Method (computer science)|method]]''' cannot be [[Method overriding|overridden]] or hidden by subclasses.<ref>[http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.3.3]</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:
<source lang="java">
public class MyClassBase
{
public void myMethodm1() {...}
public final void myFinalMethodm2() {...}
 
public classstatic AnotherClass extendsvoid MyClassm3() {...}
public static final void myMethodm4() {...} // Ok
public final void myFinalMethod() {...} // forbidden
}
 
public class Derived extends Base
{
public void m1() {...} // Ok, overriding Base#m1()
public void m2() {...} // forbidden
 
public static void m3() {...} // OK, hiding Base#m3()
public finalstatic void myFinalMethodm4() {...} // forbidden
</source>