Junior — Middle
What is the significance of the final modifier for declared classes and interfaces in Java?
sobes.tech AI
Answer from AI
In Java, the final modifier for a class means that this class cannot be inherited — that is, you cannot create a subclass from a class declared as final. This is used to prevent extension of the class, which can be important for security, immutability of behavior, or optimization.
For interfaces, the final modifier is not applicable, as interfaces are meant for implementation, and they cannot be declared as final. Attempting to declare an interface as final will result in a compilation error.
Example:
final class ImmutableClass {
// cannot create a class that inherits from ImmutableClass
}
// Attempting to do so will cause an error:
// class SubClass extends ImmutableClass {} // Compilation error