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.
The public access modifier allows unrestricted access to a class, method, variable, or constructor. It can be accessed from anywhere within the program.
public class ClassName { // Class implementation } public returnType methodName() { // Method implementation } public dataType variableName;
public class Circle { public double radius; public void calculateArea() { // Area calculation implementation } }
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.
private class ClassName { // Class implementation } private returnType methodName() { // Method implementation } private dataType variableName;
public class Circle { private double radius; private void calculateArea() { // Area calculation implementation } }
The protected access modifier allows access to the class, method, variable, or constructor within the same package or subclasses in different packages.
protected class ClassName { // Class implementation } protected returnType methodName() { // Method implementation } protected dataType variableName;
protected class Shape { protected void displayShape() { // Display shape implementation } } public class Circle extends Shape { public void displayCircle() { displayShape(); // Accessing protected method from superclass } }
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.
class ClassName { // Class implementation } returnType methodName() { // Method implementation } dataType variableName;
class Rectangle { int length; int width; void calculateArea() { // Area calculation implementation } }
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.