top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Final Class in Java

Introduction

A class that cannot be further extended is called a final class in Java. A final class is declared using the final keyword. An abstract class cannot be a final class, hence, it can only be created when the class possesses a completion in nature. The final class in Java example list is mostly made of wrapper classes like String, Integer, and so on.

There cannot be any subclass inheritances of a final class, as the compiler will display error notes on trying to inherit a final class during a compilation. Java's final keywords help in creating a final class with the help of assigning a complete definition of the class. The final keyword in Java is applied to restrict the user.

Overview

The final class in Java can be used by defining a final parameter to declare the final keyword. The inbuilt final class in Java does not allow the inheritance of subclasses, the final classes cannot be inherited by any subclass. 

This tutorial provides an uncomplicated guide to the concepts of the final class in Java, including a vivid explanation of the method and information on how to execute it. 

Final Variables

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.

Java final Method 

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.

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

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? 

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 final () in Java?

The final keyword or final() in Java is a non-access modifier that makes the classes, methods, and attributes unchangeable. It is useful in keeping the stored values of the variables always the same, as final keywords restrict the possibility of overriding or inheriting after declaration. 

  1. What is static in Java?

The static keyword is a non-access modifier in Java that can be used in methods and attributes. You can access the static attributes or methods without any created class object. Static classes are nested and do not possess reference requirements from the outer class. It can only access the static members of the outer class. 

  1. Can the final be null in Java?

Yes, you can attain a null0valued final in Java by initializing a blank final variable in the constructor. Using an instance-initializer block can generate similar outcomes. 

Leave a Reply

Your email address will not be published. Required fields are marked *