Google Search

Saturday, October 24, 2015

What is rule of accessibility at java?

We can have all the four access modifiers for class member variables and methods. However member access modifier rules get applied after the class level access rules. For example, if class is having default access, then it will not be visible in other packages and hence methods and variables of the class will also be not visible.
public keyword
If class member is “public” then it can be accessed from anywhere. The member variable or method is accessed globally. This is simplest way to provide access to class members, however we should take care in using this keyword with class variables otherwise anybody can change the values. Usually class variables are kept as private and getter-setter methods are provided to work with them.
private keyword
If class member is “private” then it will be accessible only inside the same class. This is the most restricted access and the class member will not be visible to the outer world. Usually we keep class variables as private and methods that are intended to be used only inside the class as private.
protected keyword
If class member is “protected” then it will be accessible only to the classes in the same package and to the subclasses. This modifier is less restricted from private but more restricted from public access. Usually we use this keyword to make sure the class variables are accessible only to the subclasses.

No comments:

Post a Comment