Senior
How to protect against inheritance and overriding of getters (so that colleagues cannot override the getter and remove protective copying)?
sobes.tech AI
Answer from AI
In Java, it is not possible to completely prevent overriding a getter if it is not declared as final, but there are several approaches for protection:
- Declare the getter as final — then subclasses cannot override it.
public class MyClass {
private final List<String> data = new ArrayList<>();
public final List<String> getData() {
return new ArrayList<>(data); // defensive copying
}
}
-
Make the class final — then inheritance and overriding are impossible.
-
If the class should be inheritable but the getter should not, you can make the getter private or package-private and provide access through other methods.
-
Use composition instead of inheritance to control behavior.
Thus, the simplest and most reliable way is to declare the getter as final, so no one can override it and remove the defensive copying.