✏️ Explanatory Question

What is final class?

👁 868 Views
📘 Detailed Answer
💡

Answer with Explanation

In Java, a final class is a class that cannot be extended or subclassed. When a class is declared as final, it means that it cannot have any subclasses. This is done to prevent further modification or extension of the class.

Here's an example of declaring a final class in Java:


final public class FinalClassExample {
    // Class members and methods
}

In this example, FinalClassExample is declared as a final class. If you attempt to extend this class, the compiler will generate an error.


// This will result in a compilation error
public class SubClass extends FinalClassExample {
    // Subclass members and methods
}

Common use cases for declaring a class as final include:

  1. Security: To prevent sensitive classes from being extended and potentially compromised.

  2. Design Decision: When the design of the class is intended to be complete and should not be altered.

  3. Performance: The compiler and runtime environment may be able to make certain optimizations based on the immutability of a final class.

It's important to note that the final keyword can be applied not only to classes but also to methods and variables in Java, each with its own implications.