Java Access Modifiers

htt‮sp‬://www.theitroad.com

Access modifiers are used to control the visibility and accessibility of classes, methods, and fields in Java. By setting the appropriate access modifiers, you can ensure that your code is more secure, maintainable, and extensible.

Java provides four types of access modifiers to control the visibility and accessibility of classes, methods, and fields. These are:

  1. public: The public access modifier allows a class, method, or field to be accessed from anywhere in the program. When a class or method is declared as public, it can be accessed from any other class in the program.

  2. private: The private access modifier restricts the visibility of a class, method, or field to only within its own class. When a class or method is declared as private, it cannot be accessed from any other class in the program.

  3. protected: The protected access modifier allows a class, method, or field to be accessed within its own package or by a subclass in a different package. When a class or method is declared as protected, it can be accessed from any other class in the same package, or from a subclass in a different package.

  4. default: If no access modifier is specified, then the class, method, or field has package-level accessibility. This means that it can be accessed within its own package, but not from outside the package.

Here's an example that demonstrates the use of different access modifiers:

public class MyClass {
    public int publicVar;
    private int privateVar;
    protected int protectedVar;
    int defaultVar;

    public void publicMethod() {
        // can be accessed from anywhere
    }

    private void privateMethod() {
        // can only be accessed from within the class
    }

    protected void protectedMethod() {
        // can be accessed from within the same package or from a subclass in a different package
    }

    void defaultMethod() {
        // can be accessed from within the same package
    }
}

In this example, we have a class called MyClass with four fields and four methods, each with a different access modifier. The publicVar field and publicMethod() method can be accessed from anywhere in the program. The privateVar field and privateMethod() method can only be accessed from within the same class. The protectedVar field and protectedMethod() method can be accessed from within the same package or from a subclass in a different package. The defaultVar field and defaultMethod() method can be accessed from within the same package.