Java Access Control
Overview:
In Java, access control determines the visibility and accessibility of classes, methods, and fields within the same class, package, or different packages. There are four access control modifiers in Java:
- private:
- Access is limited to the class itself.
- Fields, methods, and inner classes can be private.
- default:
- Access is limited to the package (no modifier is needed).
- Fields, methods, and classes without any specified modifier have default access.
- protected:
- Access is limited to the package and subclasses.
- Fields, methods, and classes can be protected.
- public:
- Access is not restricted.
- Fields, methods, and classes can be accessed from any class.
Examples:
Private Access Modifier:
public class MyClass {
private int privateField;
private void privateMethod() {
System.out.println("Private method");
}
}
Default Access Modifier:
class DefaultAccessClass {
// Default access fields and methods
int defaultField;
void defaultMethod() {
System.out.println("Default method");
}
}
Protected Access Modifier:
package mypackage;
public class ProtectedClass {
protected int protectedField;
protected void protectedMethod() {
System.out.println("Protected method");
}
}
Public Access Modifier:
package mypackage;
public class PublicClass {
public int publicField;
public void publicMethod() {
System.out.println("Public method");
}
}
Important Points:
Remember: Proper use of access modifiers enhances code readability, maintainability, and security by controlling the exposure of implementation details.
Comments
Post a Comment