Java access modifiers
In Java, access modifiers control the accessibility of a class or an interface by other classes and interfaces. It also controls the accessibility of the class methods and variables. By using the appropriate access modifiers, a developer can limit access to his classes and interfaces and their members.
From the previous post we remember that in Java there are three access modifiers : public, protected and private. These three access modifiers can be applied to classes, interfaces and their members (instance variables, class variables and methods).
Java classes and interfaces declared using the public access modifier are accessible to all classes from Java Universe.
The members of a class defined using the protected access modifier are accessible to :
- classes and interfaces defined in the same package;
- all derived classes (even to those defined in separate packages).
The members of a class defined without an access modifier are defined with default accessibility (also called package accessibility). The members with this level of accessibility are visible only to classes and interfaces defined in the same package.
The members of a class defined using the private access modifier are accessible only to themselves (i.e, private members are not accessible outside the class in which they are defined).
Besides the previously access levels, in Java exists the forth level of access called default access. The default access is what you get when you don’t use any access modifiers.
“The public access modifier is the least restrictive one, whereas the private modifier is the most restrictive one.”
Take away 1 : In Java programming language there are three access modifiers and four levels of access.
Take away 2 : Local variables and methods can’t be defined using access modifiers. An attempt to to this will result into a compilation error!
Rules for using access modifiers :
- A top-level class can be defined only using the public or default access modifiers;
- Private variable and method can’t be accessed from another class.