Junior — Middle
What are the access levels used for methods in object-oriented programming?
sobes.tech AI
Answer from AI
In object-oriented programming, the following access levels to methods are usually distinguished:
- public — the method is accessible from anywhere in the program.
- protected — the method is accessible within the class and its subclasses.
- private — the method is accessible only within the class itself.
Sometimes additional levels are encountered:
- package-private (in Java) — the method is accessible within the same package (absence of an access modifier).
Example in Java:
public class MyClass {
public void publicMethod() {}
protected void protectedMethod() {}
private void privateMethod() {}
void packagePrivateMethod() {} // accessible within the package
}
Such differentiation helps control encapsulation and protect the internal state of the object.