What are private, package-private, protected, and public access modifiers in java?
Java provides four access modifiers and theses modifies are used to restrict the visibility of a class, variable, or a method. Also, these access modifiers determine that other classes can access a particular variable or call a particular method of the current class. Java has provided the two levels of access controls:
- At the top level (Top level classes/interfaces)
- At the member level (variables, methods, classes/interfaces inside the top-level classes/interfaces)
And at the member level, you can use any of the four access modifiers. For example:
Now let's move further in detail about all these four access modifiers. We will start from the public access modifier that is like a free bird I guess and move toward the private access modifier that is the most restricted one.
Public Access Modifier
- Public access modifier is like a free bird. It means it is the least restrictive modifier in Java. The variables or methods that define as the public can be accessed anywhere in the world. You can define top-level classes as public.
- Making the variable public is a bad practice because in the future it is very difficult to make any change in the class as the public variable will be accessed by other classes directly. Instead of defining it public, you can define it private and provide getters and setters for accessing it from other classes.
Protected Access Modifier
- The variable, methods, constructors, or nested classes defined as protected can be accessed in the same package and outside the package in subclasses.
- You cannot define top-level classes as protected.
Package-private (no explicit modifier)
- For this modifier, there is no explicit access modifier provide by Java. If you do not declare variables, methods, constructors, or nested classes as public, protected, or private then it is by default package-private.
- As from the name it is very clear that the variables, methods, or nested classes declared without any modifier(public, protected, or private) can only be accessed inside the same package.
- You can define top-level classes with no modifier and that class will be package-private.
Private Access Modifier
- Defining variables as private and access them through getters and setters is a good coding practice.
- You can define variables, methods, constructors, or nested classes as private. Top-level classes cannot be defined as private.
- A class having a constructor private can not be subclassed that is you can extend it.
That's all about the access modifiers in java. Please do comment below if there is any query or feedback.
Comments
Post a Comment