How to use Java member accessibility modifiers

Java member accessibility modifiers in Java

In Java by using accessibility modifiers a class can control what information is accessible to other classes.
Accessibility of members can be one of the following.

  • public
  • protected
  • default(also known as package accessibility)
  • private

public Members

Public access is the least restrictive of all access modifiers .A public member is accessible everywhere , both in its class’s package and in other packages where it’s class is visible .This is true for both instances and static members.

protected Members

Protected members are accessible in the package containing class and by all subclasses of this class in any package where this class is visible . {it is less restrictive than the defaultaccessibility}

Default Accessibility Members

When no access modifier is specified for a member it is only accessible by another class in the package where it’s class is defined .Even if its class is visible in another package the member is not accessible there .

private Members

private is most restrictive of all the access modifiers .Private members are not accessible from any other class .This also applies to subclasses , whether they are in the same package or not.

It is a good design strategy to make all members variables private and provide public access methods for them.