Final (Java) - Final Methods

Final Methods

A final method can't be overridden by subclasses. 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.

Example:

public class MyClass { public void myMethod {...} public final void myFinalMethod {...} } public class AnotherClass extends MyClass { public void myMethod {...} // Ok public final void myFinalMethod {...} // forbidden }

A common misconception is that declaring a class or method final improves efficiency by allowing the compiler to directly insert the method inline wherever it is called. In fact the compiler is unable to do this because the method is loaded at runtime and might not be the same version as the one that was just compiled. Only the runtime environment and JIT compiler have the information about exactly which classes have been loaded, and are able to make better decisions about when to inline, whether or not the method is final.

Read more about this topic:  Final (Java)

Famous quotes containing the words final and/or methods:

    Sadism and masochism, in Freud’s final formulation, are fusions of Eros and the destructive instincts. Sadism represents a fusion of the erotic instincts and the destructive instincts directed outwards, in which the destructiveness has the character of aggressiveness. Masochism represents the fusion of the erotic instincts and the destructive instincts turned against oneself, the aim of the latter being self-destruction.
    Patrick Mullahy (b. 1912)

    The ancient bitter opposition to improved methods [of production] on the ancient theory that it more than temporarily deprives men of employment ... has no place in the gospel of American progress.
    Herbert Hoover (1874–1964)