Sobes.tech
Middle

What is the best way to use access modifiers in Java?

sobes.tech AI

Answer from AI

Using access modifiers:

  • private: Accessible only within the same class. Used to hide implementation details and encapsulate data.
  • default (no modifier): Accessible within the same package. Suitable for tightly related classes and members not meant to be visible outside the package.
  • protected: Accessible within the same package and subclasses (even in other packages). Used for class members meant to be extended.
  • public: Accessible from everywhere. Used for the public API of a class.

Example:

public class MyClass { // Public class, accessible everywhere

    private int privateField; // Private field, accessible only within class

    int defaultField; // Default access, accessible within package

    protected String protectedField; // Protected, accessible within package and subclasses

    public MyClass(int privateField) {
        this.privateField = privateField;
    }

    private void privateMethod() {
        // Only this class can call this method
    }

    void defaultMethod() {
        // Only classes in the same package can call this method
    }

    protected void protectedMethod() {
        // Classes in the same package and subclasses can call this method
    }

    public int getPrivateField() {
        return privateField; // Public method to access private field
    }

    public void setPrivateField(int privateField) {
        this.privateField = privateField; // Public method to modify private field
    }

    public static void main(String[] args) {
        MyClass obj = new MyClass(10);
        System.out.println(obj.getPrivateField()); // OK
        // obj.privateMethod(); // Compilation error
    }
}

class AnotherClassInSamePackage {
    void accessMethod() {
        MyClass obj = new MyClass(0);
        obj.defaultMethod(); // OK
        obj.protectedMethod(); // OK
        // obj.privateMethod(); // Compilation error
    }
}