Access Modifier

To restrict the scope of a class, constructor, variable, method, or data member, we use access modifiers. There are mainly four types of access modifiers available –

  • Default – It is set by default when no access modifier is specified. In other words, no one can access it from outside the package.
  • Public – It allows anyone to access the members of the class(on which access specifier is set) from anywhere.
  • Private – It limits its access within the class(on which access specifier is set). In other words, no one can access it from outside the class.
  • Protected – It limits its access within the class and from the class that inherits it.
 AccessSame package (Non-derived)Same package (Derived)Other package (Non-derived)Other package (Derived)
PrivateNoNoNoNo
DefaultYesYesNoNo
ProtectedyesYesNoYes
PublicYesYesYesYes