Public, Private and Protected are called access modifier in java. This are the reserved keyword in java. They are defined the access of the classes and interfaces. And when one of them are not defined then it’s called default access modifier.
Basically public exposes to classes outside the package, private hides from other classes within the package and protected is a version of public restricted only to the subclasses. Ok, Let’s see an overview how the keywords defined the access of the classes and the interfaces.
class | package | sub-class (same package) | sub-class (diff-package) | Outside World | |
public | accessible | accessible | accessible | accessible | accessible |
protected | accessible | accessible | accessible | accessible | not-accessible |
default | accessible | accessible | accessible | not-accessible | not-accessible |
private | accessible | not-accessible | not-accessible | not-accessible | not-accessible |
Explanations:
- A public member is accessible to all classes
- A protected member is accessible within all classes in the same package and within subclasses in other packages.
- A member with no access modifier is only accessible within classes in the same package.
- A private member is only accessible within the same class as it is declared.
SO, I hope you got the clarity!