Final Methods in Java


We can declare a method as final, once you declare a method final it cannot be overridden. So, you cannot modify a final method from a sub class. The main intention of making a method final would be that the content of the method should not be changed by any outsider.

This program demonstrates the concept of final methods in Java.

  • We have two classes: Super and sub, where sub is a subclass of Super. Super class has two methods: display() and finalDisplay(). The display() method is a normal method while finalDisplay() is a final method.
  • In the sub class, the display() method is overridden with its own implementation while the finalDisplay() method is not overridden as it is a final method.
  • In the main() method of the finalMethods class, an object o of the sub class is created and its display() and finalDisplay() methods are called.
  • The display() method is overridden in the sub class, so when it is called on the object o, it calls the implementation of the sub class. However, the finalDisplay() method is not overridden, so when it is called on the object o, it calls the implementation of the Super class as it is final and cannot be overridden.

Source Code

//Final Methods in Java
class Super
{
    public void display()
    {
        System.out.println("I am Super Display");
    }
    final void finalDisplay()
    {
        System.out.println("I am Super Final Display");
    }
}
class sub extends Super
{
    public void display()
    {
        System.out.println("I am Sub Display");
    }
}
 
public class finalMethods {
    public static void main(String args[])
    {
        sub o =new sub();
        o.display();
        o.finalDisplay();
    }
}
 

Output

I am Sub Display
I am Super Final Display
To download raw file Click Here

Basic Programs