Intern
What are access modifiers used for?
sobes.tech AI
Answer from AI
Access modifiers in Java regulate the visibility and accessibility of classes, interfaces, fields, methods, and constructors. They determine from where members of a class or the class itself can be accessed.
There are four main access modifiers:
public: Accessible from anywhere.protected: Accessible within its package and in all subclasses (even in other packages).default(or package-private): Accessible only within its package. If no modifier is specified, this is the default.private: Accessible only within its class.
Examples of usage:
public class PublicClass { // Accessible everywhere
public int publicField; // Accessible everywhere
public void publicMethod() { // Accessible everywhere
// ...
}
}
package com.example.package1;
class DefaultClass { // Accessible only within com.example.package1
int defaultField; // Accessible only within com.example.package1
void defaultMethod() { // Accessible only within com.example.package1
// ...
}
}
package com.example.package1;
public class ProtectedClass {
protected int protectedField; // Accessible in package1 and subclasses of ProtectedClass
protected void protectedMethod() { // Accessible in package1 and subclasses of ProtectedClass
// ...
}
}
package com.example.package2;
import com.example.package1.ProtectedClass;
class SubClass extends ProtectedClass {
void accessProtected() {
int value = protectedField; // Accessible through inheritance
protectedMethod(); // Accessible through inheritance
}
}
public class PrivateClass {
private int privateField; // Accessible only within PrivateClass
private void privateMethod() { // Accessible only within PrivateClass
// ...
}
public void publicMethodAccessingPrivate() {
privateField = 10; // Accessible inside the class
privateMethod(); // Accessible inside the class
}
}
The main purpose of using access modifiers is encapsulation, hiding implementation details, and controlling how other parts of the program interact with classes and their members. This enhances security, ease of maintenance, and code flexibility.