Understanding Java Access Modifier

In java, there are basically two types of modifiers: access modifiers and non-access modifiers. In this article, we will be talking about access modifiers in java and their scope in class, constructor, methods, variables, or data members.

There are basically 4 types of Java access modifiers. They are public, protected, private, and default. Among these four modifiers, public modifier is considered the least restrictive whereas the private modifier is considered the most restrictive. Default modifiers are the results when we don’t use any kind of modifier. We will be talking in more detail about each of these modifiers.

Private Access Modifier

Private access modifiers are considered to be the most restrictive modifiers. The member with private access modifier is accessible only within the class in which they are declared. They cannot be accessed even by the other class on the same package.

Protected Access Modifier

A derived class can inherit and access protected members of its base class. However, a derived class in a separate package cannot access protected members of the base class using a reference variable. They can be accessed only by using inheritance.

Public Access Modifier

Public access modifiers are considered to be the least restrictive access modifiers. The members with these modifiers can be accessed by all it’s derived classes as well as any unrelated classes. Whether we are calling these modifiers from the same packages or outside of the packages, this modifier can be accessed.

Default Access Modifier

Default modifiers are used when we don’t define any kind of modifier to our members. The member of these modifiers is only accessible to the classes and interfaces defined within the same packages.

Software Engineer