Skip to content

Access Modifier

Zhamri Che Ani edited this page Nov 2, 2023 · 2 revisions

A summary of the accessibility for each modifier

Modifier Class Package Subclass World
public Yes Yes Yes Yes
protected Yes Yes Yes No
no modifier Yes Yes No No
private Yes No No No

There are FOUR (4) access level modifiers. Each of these modifiers provides a different level of access control and can be applied to:

  1. classes
  2. methods
  3. constructors
  4. variables.

Here's a list of the modifiers with their accessibility:

  1. Default (no modifier): If no access modifier is specified for a class member, Java uses the default access level. Members with default access can be accessed by other members in the same package, but not from outside the package.

  2. Public: Members marked as public can be accessed from any other class in the Java program, regardless of the package the class is in.

  3. Protected: Members with protected access can be accessed by classes in the same package and by subclasses even if they are in different packages.

  4. Private: Members with private access can be accessed only within their own class.

Example for 'Default' Modifier

class DefaultClass {
    void defaultMethod() {
        // Can be accessed from any other class
    }
}

Example for 'Public' Modifier

public class PublicClass {
    public void publicMethod() {
        // Can be accessed from any other class
    }
}

Example for 'Private' Modifier

public class PrivateExample {
    private int privateVariable = 10;

    private void privateMethod() {
        // Can only be accessed within PrivateExample class
    }
}

Example for 'Protected' Modifier

public class ProtectedExample {
    protected int protectedVariable = 20;

    protected void protectedMethod() {
        // Can be accessed within the same package 
        // and in subclasses even if they are in different packages
    }
}
Clone this wiki locally