Junior — Middle
Can you give an example of using the final modifier when declaring a class in Java?
sobes.tech AI
Answer from AI
The final modifier in Java when declaring a class means that this class cannot be inherited. It is useful when you want to prevent extension of the class to preserve its behavior or security.
Example:
public final class Constants {
public static final String APP_NAME = "MyApp";
// Other constants
}
// Attempting to inherit will cause a compile error
// public class ExtendedConstants extends Constants {} // Error
In this example, the Constants class is declared as final to prevent inheritance and behavior modification.