Write A Program In Java To Demonstrate Use Of Final Class

0

Write A Program In Java To Demonstrate Use Of Final Class

Write a program in java to demonstrate use of final class

In this program, we will create a java program to understand the use of final class.


Before demonstrate the program we will understand the concept of final class.


In java, a final class is a class that cannot be extended by any other class. This means that once you declare a class as final, no other class can inherit from it.


The final keyword is used to achieve this functionality. Here's an example:


final class FinalClass {
    // Class members and methods here
}

By declaring the finalclass as final, we ensure that no other class can extend it.

This can be useful in certain situations where you want to prevent inheritance for security or design reasons. For example, if you have a class that represents a bank account, you might want to prevent other classes from extending it and potentially introducing vulnerabilities.

Here's a program in java that show the use of final class:

Program
final class ImmutableClass {
    private final String name;
    private final int age;

    public ImmutableClass(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class FinalClassExample {
    public static void main(String[] args) {
        ImmutableClass person = new ImmutableClass("John", 20);
        System.out.println("Name: " + person.getName());
        System.out.println("Age: " + person.getAge());

        // Uncommenting the following line would result in a compile error
        // since ImmutableClass cannot be subclassed
        // class SubClass extends ImmutableClass {}
    }
}

Output
Name: John Age: 20

Explanation
In this example, we have a final class called immutableclass that has two private final fields name and age. The class has a constructor that initializes these fields and two getter methods that return the values of these fields.

In the finalclassexample class, we create an instance of the immutableclass and print its name and age fields. We also try to create a subclass of immutableclass by uncommenting the code, but it results in a compile error since immutableclass is declared final and cannot be subclassed.

This example demonstrates the use of a final class to create an immutable object whose state cannot be changed after it is created. By making the class final, we also prevent any modifications to its behavior through subclassing.

❤️ I Hope This Helps You Understand, Click Here To Do More Exercise In Java Programming.


Post a Comment

0Comments
Post a Comment (0)