How do you use access modifiers (public, protected, default, private) with a simple code example?

Access modifiers in Java are used to set the accessibility and visibility of classes, methods, and variables. The four main access modifiers are:

  • Public: Accessible from any other class.
  • Protected: Accessible within the same package and subclasses.
  • Default: (no modifier) Accessible only within the same package.
  • Private: Accessible only within the class itself.

Here is a simple example demonstrating the use of each access modifier:


class Example {
    // Public variable
    public String publicVar = "I am public!";
    
    // Protected variable
    protected String protectedVar = "I am protected!";
    
    // Default variable
    String defaultVar = "I am default!";
    
    // Private variable
    private String privateVar = "I am private!";
    
    public void display() {
        System.out.println(publicVar);
        System.out.println(protectedVar);
        System.out.println(defaultVar);
        System.out.println(privateVar);
    }
}

class Test {
    public static void main(String[] args) {
        Example example = new Example();
        example.display();
        
        // Accessing variables
        System.out.println(example.publicVar); // Accessible
        // System.out.println(example.protectedVar); // Not accessible
        // System.out.println(example.defaultVar); // Not accessible
        // System.out.println(example.privateVar); // Not accessible
    }
}

Access Modifiers Public Protected Default Private Java Example