Java-Access Modifiers

Access Modifiers

We can define the scope of a variable or method or class by using the access modifiers. The scope of an entity is the region in which it is accessible. Java has the following four levels of controlling access to variables, methods and classes.

1. Private Access

Variables are generally declared with the access control modifier private. In such a case, they can be accessed only by methods of the class in which they are defined. Methods are rarely declared to be of type private. Such a method can be invoked only by the methods in the class in which that method is defined.

2. Public Access

When the public access control modifier is specified for a variable or method or class, it can be accessed by methods of any class in the same package or a different package. Methods are generally declared to be public. Classes are provided public access, if they should have very wide visibility.(i.e. they should be accessible from any class in the same package or a different package).

3. Package Access

If we do not specify an access control modifier, then the default is package access. If a variable or method or class has package access, then it can be accessed by all methods of classes in the same package. The package access is a good default option for classes, but this access is not preferable for variables and methods. It is better that variables are private and methods are public.

4. Protected Access

When the protected access control modifier is specified for a variable or method in a class, it can be accessed by the methods of the same class, subclasses in the same package and non-subclasses in the same package. Furthermore, protected variables and methods can be accessed by all methods of subclasses in different packages. The visibility level of a protected field lies in between the public access and package access. Note that non-subclasses in other packages cannot access the protected members.

Conceptual View of a Access Modifiers

Leave a Comment