n Java, access modifiers are keywords that define the visibility and accessibility of classes, methods, and variables. They control which other classes can access a particular class, method, or variable. There are four main access modifiers in Java:
- Default (Package-Private):
- If no access modifier is specified, the default access level is package-private. This means that the class, method, or variable is accessible within the same package but not outside of it.
class Example {
int x; // Package-private variable
void method() { // Package-private method
// ...
}
}
Public:
- The
public
access modifier makes the class, method, or variable accessible from anywhere. This includes other packages.
public class PublicExample {
public int y; // Public variable
public void publicMethod() { // Public method
// ...
}
}
Private:
- The
private
access modifier restricts the visibility to only within the class where it is declared. It is not accessible from outside the class, including subclasses.
public class MyClass {
private int z; // Private variable
private void privateMethod() { // Private method
// ...
}
}
Protected:
- The
protected
access modifier allows access within the same package, as well as in subclasses (even if they are in different packages).
package com.example;
public class ParentClass {
protected int protectedVariable; // Protected variable
protected void protectedMethod() { // Protected method
// ...
}
}
package com.example.subpackage;
public class ChildClass extends ParentClass {
void accessProtected() {
protectedVariable = 10; // Accessing protected variable from the superclass
protectedMethod(); // Accessing protected method from the superclass
}
}
Here’s a summary of the access permissions for each access modifier:
Access Modifier | Within Class | Within Package | Outside Package (Subclass) | Outside Package (Non-subclass) |
---|---|---|---|---|
Default | Yes | Yes | No | No |
Public | Yes | Yes | Yes | Yes |
Private | Yes | No | No | No |
Protected | Yes | Yes | Yes | No |
It’s important to choose the appropriate access level based on the design and encapsulation principles to ensure proper data hiding and abstraction in your Java programs.