Access Modifiers in Java

Access modifiers define the accessibility levels of classes, methods, variables, and constructors in Java. They help in encapsulating code, enforcing data hiding, and controlling the visibility of program elements.

public

The public access modifier allows unrestricted access to a class, method, variable, or constructor. It can be accessed from anywhere within the program.

Syntax
public class ClassName {
    // Class implementation
}
public returnType methodName() {
    // Method implementation
}
public dataType variableName;
Example
public class Circle {
    public double radius;

    public void calculateArea() {
        // Area calculation implementation
    }
}
private

The private access modifier restricts access to the class, method, variable, or constructor within the same class. It cannot be accessed from outside the class.

Syntax:
private class ClassName {
    // Class implementation
}
private returnType methodName() {
    // Method implementation
}
private dataType variableName;
Example
public class Circle {
    private double radius;
    private void calculateArea() {
        // Area calculation implementation
    }
}
protected

The protected access modifier allows access to the class, method, variable, or constructor within the same package or subclasses in different packages.

Syntax
protected class ClassName {
    // Class implementation
}
protected returnType methodName() {
    // Method implementation
}
protected dataType variableName;
Example
protected class Shape {
    protected void displayShape() {
        // Display shape implementation
    }
}
public class Circle extends Shape {
    public void displayCircle() {
        displayShape(); // Accessing protected method from superclass
    }
}
Default (No Modifier)

The default access modifier (also known as package-private) allows access to the class, method, variable, or constructor within the same package only. It is used when no access modifier is explicitly specified.

Syntax
class ClassName {
    // Class implementation
}
returnType methodName() {
    // Method implementation
}
dataType variableName;
Example
class Rectangle {
    int length;
    int width;
    void calculateArea() {
        // Area calculation implementation
    }
}
Note

Access modifiers in Java provide control over the visibility and accessibility of classes, methods, variables, and constructors. They help in enforcing encapsulation and data hiding principles. By understanding the syntax and appropriate usage of access modifiers, you can write secure and maintainable Java code.