access control
access control
fields based on their visibility or scope. Java provides several access modifiers to help define
how and where a class or member can be accessed. There are four main access modifiers in
Java:
1. public
Visibility: Any class or method marked as public can be accessed from any other
class, regardless of the package.
Usage: Typically used for methods or classes that need to be accessible from
anywhere in the application.
2. protected
Visibility: Members marked as protected can be accessed within the same package
or by subclasses (even if they are in a different package).
Usage: Useful for inheritance, when you want to allow access to certain members in
child classes, but not to the general public.
class Example {
int number; // default access
Visibility: Members marked as private can only be accessed within the same class.
No external class, including subclasses, can access private members directly.
Usage: Used to encapsulate data and hide it from other classes.