In Java, access modifiers are used to control the visibility of members of a class, such as variables, methods, and constructors. There are four access modifiers in Java:
Public: Members with public access can be accessed by any class, regardless of the package it is in.
Protected: Members with protected access can be accessed by classes in the same package and by subclasses of the class in any package.
Package-private: Members with package-private access can be accessed by classes in the same package.
Private: Members with private access can only be accessed by the class in which they are declared.
Here is a table summarizing the visibility of the four access modifiers in Java:
Access modifier
Visibility
Public
Any class, whether it is in the same package or in a different package.
Protected
Any class in the same package and subclasses of the class in any package.
Package-private
Any class in the same package.
Private
Only the class in which it is declared.
The default access modifier in Java is package-private. This means that members that are declared without an access modifier are only accessible to classes in the same package.
When choosing an access modifier, you should consider the following factors:
Do you want the member to be accessible to other classes? If yes, then use public or protected.
Do you want to encapsulate the implementation details of the member? If yes, then use private.
Do you want to allow subclasses to access the member? If yes, then use protected.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In Java, access modifiers are used to control the visibility of members of a class, such as variables, methods, and constructors. There are four access modifiers in Java:
Here is a table summarizing the visibility of the four access modifiers in Java:
The default access modifier in Java is package-private. This means that members that are declared without an access modifier are only accessible to classes in the same package.
When choosing an access modifier, you should consider the following factors: