View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Final Class in Java: Meaning, Syntax, Methods & Examples

Updated on 24/06/202514,538 Views

Can you prevent a class in Java from being inherited—and why would you want to?
That’s the exact purpose of a final class in Java. When you declare a class as final, you restrict other classes from extending it. This is especially useful when you want to maintain security, enforce immutability, or prevent modification of core logic.

In this blog, you’ll explore what a final class in Java is, how it differs from final methods and variables, and when it should be used. You’ll also see syntax, real-life examples, and key advantages of using final classes in enterprise-level Java applications. Whether you’re preparing for interviews or building secure APIs, understanding final in Java is essential.

Want to master core Java and object-oriented programming principles? Check out upGrad’s Software Engineering Courses to learn Java, design patterns, and best practices from industry experts.

Before directly proceeding to the final class in JAVA, please check the types of variables in Java and the final keywords in JAVA.

What is Final Variables in Java?

When the final keyword is used to declare a variable, its value cannot be modified anymore, making it a constant variable, which makes it mandatory to initialize a final variable. Final variables can be portrayed as references where the variable cannot be further changed or rebounded to reference another value.

However, the object's internal state spotted by the reference variable can be changed by adding or removing elements from the final collection or the final array. Final variables are presented using upper case characters, and the words are separated through underscores. It plays an important role in the operations list of final class in Java.

Initializing a final variable is necessary to prevent the compiler from throwing issues like a compile-time error. Final variables can be initialized only once, the process can be conducted with the help of an initializer or by using assessment statements. There are three primary ways to initialize a final variable, namely:

  • Initializing during the declaration
  • Using the constructor or in an instance-initializer block
  • Through a static block

Example of final variable

Here is an example of using the final keyword to declare a variable as a constant:

Code:

public class Circle {
    private final double PI = 3.14159; // Constant variable
    
    private double radius;
    
    public Circle(double radius) {
        this.radius = radius;
    }
    
    public double calculateArea() {
        return PI * radius * radius;
    }
    
    public static void main(String[] args) {
        Circle circle = new Circle(5.0);
        double area = circle.calculateArea();
        System.out.println("Area of the circle: " + area);
    }
}

In this example, the PI variable is declared final, indicating that its value cannot be changed after initialization. It is assigned the value 3.14159, the constant value for pi. By making it final, we ensure that the value of PI remains constant throughout the execution of the program.

The calculateArea() method uses the PI constant to calculate the area of the circle. In the main method, we create an instance of the Circle class and calculate the area, demonstrating the usage of the final variable as a constant.

WHat is Java final Method in JAVA?

The final method in Java is a method that cannot be overridden by any subclass. Once a method is declared as final in a superclass, it is considered a complete and unchangeable implementation of that method.

Final methods are often used when you want to prevent subclasses from modifying or altering the behavior of a particular method defined in a superclass. It provides a way to enforce consistency and prevent method overriding.

Example of final method

Here is an example of using the final keyword with a method in Java:

Code for Parent.java file:

public class Parent {
    public final void printMessage() {
        System.out.println("This is a final method in the Parent class.");
    }
}

Code for Child.java file:

public class Child extends Parent {
    public static void main(String[] args) {
        Child child = new Child();
        child.printMessage();
    }
}

In this example, the printMessage() method in the Parent class is declared final. This means that any subclass cannot override it.

WHat is Java final Class?

The final class represents the end of the inheritance hierarchy, as no other class can inherit from it. Final classes are often used for utility classes or classes with a specific implementation that should not be altered or extended. Final classes also offer performance benefits as the compiler can further optimize them.

Example of final class

Code for FinalClass.java file:

public final class FinalClass {
    public void printMessage() {
        System.out.println("This is a final class.");
    }
}

Code for Main.java file:

public class Main {
    public static void main(String[] args) {
        FinalClass finalObj = new FinalClass();
        finalObj.printMessage();
    }
}

The FinalClass is declared as final in the above program, meaning it cannot be subclassed. The printMessage() method in FinalClass prints the message "This is a final class." The Main class contains the main method, which creates an instance of FinalClass called finalObj. It then calls the printMessage() method on finalObj to display the message "This is a final class."

Advantages of the Final Class in Java

The final class in Java is used in providing security as it has no chances of extensions or inheritance by other classes. It is an immutable and complete class that can ensure the safety of data elements by preventing changes from external sources. The major advantages of final class in Java are enlisted below:

  • Ensures Data Immutability: Once a reference or variable is marked using the final keyword, its value cannot be further modified after it gets assigned, ensuring the stored data's unchangeability.
  • Improves Performance and Productivity: Another use of final class in Java is improving the performance by optimizing the codes more efficiently.
  • Simplification of the Codes: Developers make the codes easily understandable and quickly reasonable by declaring the methods, variables, or classes as final, simplifying the code debugging and analysis procedures.
  • Enhances Security Aspects: It prevents malicious activities and modifications to the stored data.
  • Promotes Reusability of Codes: Subclasses cannot override the final class values, allowing the reuse of codes and reducing duplicate implementations.

How to Create Final Classes in JAVA?

Let us learn how to use the final class in Java with examples.

Example 1: How to Use final class?

To use the final class, it must be first declared as final.

In the instance of the below program, it will have a private message field, which will also be marked as final. This makes the field a constant that cannot be changed after initialization.

Code:

public final class FinalClass {
    private final String message;

    public FinalClass(String message) {
        this.message = message;
    }

    public void displayMessage() {
        System.out.println(message);
    }

    public static void main(String[] args) {
        FinalClass finalObj = new FinalClass("Hello, I am a final class!");
        finalObj.displayMessage();
    }
}

The constructor can then assign a parameter to the message field. We will then add a displayMessage() method that prints the message to the console.

Finally, we will add the main method, which will contain the usage of the final class. It creates an instance of the final class called finalObj and passes the message "Hello, I am a final class!" to the constructor.

Finally, the displayMessage() method will be called on the finalObj, which outputs the message to the console.

Example: 2 What happens if we try to inherit from a final Class?

If we attempt to inherit from a final class in Java, it will result in a compilation error. Let us take a look at an example:

Code for FinalClass.java file:

public final class FinalClass {
    public void displayMessage() {
        System.out.println("This is a final class.");
    }
}

Code for SubClass.java file:

public class SubClass extends FinalClass {
    // Attempting to inherit from a final class will result in a compilation error.
    // Uncommenting the code below will result in a compilation error.
    /*
    public void displayMessage() {
        System.out.println("This is a subclass of FinalClass.");
    }
    */

    public static void main(String[] args) {
        FinalClass finalObj = new FinalClass();
        finalObj.displayMessage();

        SubClass subObj = new SubClass();
        subObj.displayMessage();
    }
}

In this example, the FinalClass is declared final, indicating it cannot be subclassed. The SubClass is an attempt to inherit from the FinalClass. However, this will result in a compilation error.

The compiler will generate an error message similar to: "cannot inherit from final FinalClass". This error occurs because the final keyword prevents the FinalClass from being extended or subclassed.

Declining a class as final prevents further inheritance, ensuring that the class cannot be extended and its behavior remains unchanged. It helps maintain the integrity and immutability of the class, preventing modifications or unintended changes in its implementation.

Conclusion

The final class in Java is an effective tool that improves the code quality, adds security, and simplifies the code. Using the final class helps in restricting class inheritance by preventing extensions. Trying to inherit final classes can cause the compiler to cause a compilation error. You can learn more about different Java operations by joining effective training programs.

There are various educational projects on multiple platforms, including narratives in local languages for further clarity, like the online tutorials on the final class in Java in Hindi. You can check out the courses on Java from upGrad if you are passionate about developing your programming skills.

FAQs

1. What is a final class in Java?

A final class in Java is a class that cannot be extended or inherited. Once declared final, no other class can subclass it. This ensures the class’s behavior remains unchanged and is often used in secure or utility-based Java code.

2. Why do we use final classes in Java?

Final classes in Java are used to prevent inheritance and protect the original class design. They're ideal for creating immutable classes or securing critical utility classes that shouldn't be modified or extended by other parts of the program.

3. What is the syntax to declare a final class in Java?

To declare a final class, use the final keyword before the class name:

javaCopyEditfinal class ClassName { }  

This ensures that the class cannot be inherited by any subclass, enforcing complete encapsulation.

4. What happens if you try to extend a final class in Java?

If you try to extend a final class in Java, the compiler will throw an error. Java does not allow inheritance of final classes, making them non-extensible and ensuring their logic remains intact and secure.

5. What is the difference between final class and final method in Java?

A final class can’t be extended, while a final method can’t be overridden. Both enforce restrictions on inheritance but at different levels—class-level restriction versus method-level customization control within subclassing.

6. Can a final class in Java have final methods?

Yes, a final class in Java can contain both final and non-final methods. However, since the class itself can’t be extended, marking its methods as final has limited impact beyond internal clarity or intent.

7. What are some real-world examples of final classes in Java?

Classes like java.lang.String, java.lang.Math, and java.lang.Integer are final classes in Java. These classes are designed to be immutable and secure, making them reliable for use in all types of Java programs.

8. Can a final class in Java implement interfaces?

Yes, a final class can implement one or more interfaces. While it cannot be subclassed, it can still provide implementations for all methods declared in the interfaces, making it versatile yet non-inheritable.

9. Is it possible to override methods of a final class in Java?

No, you cannot override methods of a final class in Java because the class itself cannot be extended. This ensures that no child class can alter or interfere with its existing behavior.

10. Can you create a final variable in a final class in Java?

Yes, you can declare final variables inside a final class. Final variables are constants, and their values cannot be changed once assigned. They’re commonly used for defining fixed configurations or constants in Java.

11. What are the advantages of final classes in Java?

Final classes in Java offer advantages like security, immutability, and predictable behavior. They prevent accidental extension, allow runtime optimizations, and are useful in designing reliable APIs and utility classes that should not be modified.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Pavan Vadapalli

Author|900 articles published

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology s....

image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.