Access modifiers in Java are keywords that define the visibility and accessibility of classes, methods, and variables. There are three main access modifiers in Java:
-
public
: Apublic
member is visible and accessible from any class in the program, regardless of package or inheritance relationships. For example, if you declare apublic
method in a class, any other class in the program can call that method. -
private
: Aprivate
member is only visible and accessible within the same class where it is declared. This means that no other class in the program can access or modify aprivate
member. For example, if you declare aprivate
variable in a class, no other class can read or write that variable. -
protected
: Aprotected
member is visible and accessible within the same class and within any subclass of that class. This means that aprotected
member can be accessed by any class that inherits from the class where it is declared. However, it cannot be accessed by classes in different packages that do not inherit from the class.
Here’s an example that demonstrates the use of access modifiers:
public class Person {
public String name; // public variable
private int age; // private variable
protected String address; // protected variable
public Person(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
public void sayHello() { // public method
System.out.println("Hello, my name is " + name);
}
private void secretMethod() { // private method
System.out.println("This is a secret method");
}
protected void protectedMethod() { // protected method
System.out.println("This is a protected method");
}
}
In this example, the Person
class has three instance variables (name
, age
, and address
) and three methods (sayHello()
, secretMethod()
, and protectedMethod()
). The name
variable is public
, which means that it can be accessed from any class. The age
variable is private
, which means that it can only be accessed from within the same class. The address
variable is protected
, which means that it can be accessed from within the same class and within any subclass of the Person
class.
The sayHello()
method is public
, which means that it can be called from any class. The secretMethod()
method is private
, which means that it can only be called from within the same class. The protectedMethod()
method is protected
, which means that it can be called from within the same class and within any subclass of the Person
class.
Access modifiers are an important part of Java’s encapsulation mechanism, and they allow you to control the visibility and accessibility of your class’s members. By using access modifiers effectively, you can create more secure and maintainable code that is easier to understand and modify.