Dremendo Tag Line

Final Class and Method in Java Programming

OOPs in Java

In this lesson, we will understand what is Final Class and Final Method in Java and how to implement them in programming along with some examples.

What is Final Class in Java?

A final class is a class that cannot be subclassed. It means that if a class is declared as final, no other class can extend it.

Example

final class Message
{
    public void show()
    {
        System.out.println("I am method inside a final class");
    }
}

In the above example, the class Message is declared as final, which means that it cannot be subclassed. Any attempt to extend the Message class into another class will result in a compile-time error. See the example given below.

Example

class Demo extends Message
{
    // This will give a compile-time error: Cannot inherit from final Message
}

We know that we cannot extend a final class, but we can create its object.

Example

final class Message
{
    public void show()
    {
        System.out.println("I am method inside a final class");
    }
}

public class Example
{
    public static void main(String args[])
    {
        Message x=new Message();
        x.show();
    }
}

Output

I am method inside a final class
video-poster

What is Final Method in Java?

A final method is a method that a subclass cannot override. It means that if a method is declared as final, any child class of the parent class that contains the final method will be unable to override it.

Example

class Message
{
    final public void show()
    {
        System.out.println("I am method inside a final class");
    }
}

class Data extends Message
{
    public void show()
    {
        // This will give a compile-time error:
        // show() in Data cannot override show() in Message
    }
}

We know that we cannot override a final method in a subclass, but we can call it in subclass.

Example

class Message
{
    final public void show()
    {
        System.out.println("I am a final method");
    }
}

class Data extends Message
{
    public void display()
    {
        // Calling the final show() method of the Message class
        show();
    }
}

public class Example
{
    public static void main(String args[])
    {
        Data x=new Data();
        x.display();
    }
}

Output

I am a final method