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

  • Post author:
  • Post category:Interview Questions
  • Post last modified:July 7, 2021
  • Reading time:1 mins read

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.

classpackagesub-class
(same package)
sub-class
(diff-package)
Outside World
publicaccessibleaccessibleaccessibleaccessibleaccessible
protectedaccessibleaccessibleaccessibleaccessiblenot-accessible
defaultaccessibleaccessibleaccessiblenot-accessiblenot-accessible
privateaccessiblenot-accessiblenot-accessiblenot-accessiblenot-accessible
access modifier in java cheatsheet

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!