by BehindJava
What are Access Specifiers in Java
In this blog, we are going to learn about Access Specifiers in Java.
Access Specifiers in Java
-
Public: Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program, whether these classes are in the same package or in another package.
- Public Specifiers achieves the highest level of accessibility.
-
Protected: Fields, methods and constructors declared protected in a superclass can be accessed only by classes in same package as well as by subclasses in other packages.
- Classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected member’s class.
- The protected access modifier can be applied on the data member, method and constructor. It can’t be applied on the class/interface. Like default case+can access subclass of different package
- Methods and fields declared as protected can only be accessed by the subclasses in other package or any class within the package of the protected members’ class.
-
Default: Default modifier is accessible only within package.
- When you don’t set access specifier for the element, it will follow the default accessibility level.
- There is no default specifier keyword.
- Can access class, method, or field which belongs to same package,but not from outside this package.
- Classes, variables, and methods can be default accessed(accessible only by classes in same package).
-
Private: Cannot be accesses by anywhere outside the enclosing class.
- Has lowest level of accessibility and not visible within subclasses and are not inherited by subclasses(within package and in different package).
- Helps to achieve encapsulation and hide data from the outside world.
- Here, 2 classes A and Simple are defined. A class contains private data member and private method.As we are accessing these private members from outside class, so there is compile time error.
- The private access modifiers is accessible only within the class.
//example of private access modifier
class A{
private int data=40;
private void msg()
{
System.out.println("Hello java");
}
}
public class Simple{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data); // Compile Time Error
obj.msg(); // Compile Time Error
} }