What is the difference between public, protected, package-private and private in Java?

Technology CommunityCategory: JavaWhat is the difference between public, protected, package-private and private in Java?
VietMX Staff asked 3 years ago
  • Private – Like you’d think, only the class in which it is declared can see it
  • Package Private – Can only be seen and used by the package in which it was declared. This is the default in Java (which some see as a mistake)
  • Protected – Package Private + can be seen by subclasses or package member
  • Public – Everyone can see it
______________________________________________________________
|           │ Class │ Package │ Subclass │ Subclass │ World  |
|           │       │         │(same pkg)│(diff pkg)│        |
|───────────┼───────┼─────────┼──────────┼──────────┼────────|
|public     │   +   │    +    │    +     │     +    │   +    | 
|───────────┼───────┼─────────┼──────────┼──────────┼────────|
|protected  │   +   │    +    │    +     │     +    │        | 
|───────────┼───────┼─────────┼──────────┼──────────┼────────|
|no modifier│   +   │    +    │    +     │          │        | 
|───────────┼───────┼─────────┼──────────┼──────────┼────────|
|private    │   +   │         │          │          │        |
|___________|_______|_________|__________|__________|________|
 + : accessible         blank : not accessible