Sobes.tech
Junior — Middle

Is it possible to restrict the accessibility of getter methods in Java to make them less public?

sobes.tech AI

Answer from AI

In Java, access modifiers are applied to methods, including getters, to restrict their visibility. If you want to make a getter less public, you can:

  • Declare the getter with the protected or package-private (no modifier) access modifier to restrict access within the package or subclasses.
  • Use private for complete concealment of the getter.

For example:

class MyClass {
    private int value;

    // Package-private getter
    int getValue() {
        return value;
    }
}

Thus, getters do not necessarily have to be public. This allows controlling who and how can access the internal data of the object.

Is it possible to restrict the accessibility of… - sobes.tech