Junior — Middle
What is the role and purpose of access modifiers in programming?
sobes.tech AI
Answer from AI
Access modifiers in programming define the level of visibility and accessibility of classes, methods, and fields to other parts of the program. In Java, for example, they help control encapsulation, ensuring data protection and preventing unwanted interactions between components.
Main access modifiers in Java:
- public — accessible to everyone.
- private — accessible only within the current class.
- protected — accessible within the package and subclasses.
- default (package-private) — accessible within the package.
Example:
public class Person {
private String name; // accessible only within Person
public String getName() { // accessible from anywhere
return name;
}
}
This control helps create reliable and maintainable programs by restricting direct access to internal data and methods.