Java Type of Access Modifiers

https:/‮figi.www/‬tidea.com

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

Java has four types of access modifiers:

  1. public: The public modifier makes the class, method or field accessible from anywhere in the program.

  2. private: The private modifier makes the class, method or field accessible only within the class it is declared in.

  3. protected: The protected modifier makes the class, method or field accessible within the same package or any subclasses outside the package.

  4. default: If no access modifier is specified, it is known as package-private or default access. This means that the class, method or field is accessible only within the same package.

Here's an example of how the different access modifiers can be used for a class, its fields and methods:

public class MyClass {
    public int publicVar;  // can be accessed from anywhere
    private int privateVar; // can only be accessed within this class
    protected int protectedVar; // can be accessed within this package and any subclasses outside the package
    int defaultVar; // can be accessed only within the same package

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

    private void privateMethod() { // can only be accessed within this class
        // method body
    }

    protected void protectedMethod() { // can be accessed within this package and any subclasses outside the package
        // method body
    }

    void defaultMethod() { // can be accessed only within the same package
        // method body
    }
}