Sobes.tech
Junior — Middle

How does declaring a class with the final modifier in Java differ?

sobes.tech AI

Answer from AI

In Java, the final modifier when declaring a class means that this class cannot be inherited. It prevents the creation of subclasses from this class.

Example:

public final class MyClass {
    // class body
}

// Attempting to inherit will cause a compilation error
// class SubClass extends MyClass {} // Error!

Using final for a class is useful when you want to guarantee the immutability of the class's behavior and avoid unwanted extensions, which increases the safety and predictability of the code.

How does declaring a class with the final modifier in… - sobes.tech