JAVA-Access Modifiers

Access Modifiers Summary

Maleesha Thalagala
2 min readJan 25, 2021
Photo by Max Duzij on Unsplash

Java has a wide variety of modifiers like,

· Java Access Modifiers

· Non-Access Modifiers

Here we are talking about java access modifiers.Java gives permission to set access levels for classes, variables, methods, and constructors. There are four access levels and those are :

1. Default -Visible to the package.

2. Private-Visible to the class.

3. Public- Visible to the world.

4. Protected- Visible to the package and all subclasses.

Default Access Modifier

If we do not use an access modifier for a class, method, variable, etc; it will be declared as the default access modifier. So this variable or method which is declared without an access modifier is available to any other class in the same package.

Private Access Modifier

If a method, variables, and constructors that are declared with the private keyword can be accessed within the declared class itself. The private access modifier is considered the most restrictive access level. Variables that are declared with this keyword can be accessed outside the class, but it can be done if public getter methods are present within the class.

Note: Interfaces and class cannot be private.

Public Access Modifier

A method, class, constructor or interface, etc; declared public can be accessed from any other class. If we try to access public class in a different package, then the public class still needs to be imported. All public methods and variables of a class are inherited by its subclasses because of the inheritance.

Protected Access Modifier

When we declared variables, methods, and constructors using protected access modifier in a superclass can be accessed only by the subclasses that are in any package or any class within the package of the protected members’ class.

Note: Interfaces and class cannot be protected.

Summary Table

--

--

Maleesha Thalagala

Software Engineer | Tech Enthusiast | Freelance Writer