Java provides a number of access modifiers to help you set the level of access you want for classes as well as the fields, methods and constructors in your classes. A member has package or default accessibility when no accessibility modifier is specified.
Access Modifiers
1. private2. protected
3. default
4. public
Public access modifier
Fields, methods and constructors declared public 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.Private access modifier
The private fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods or constructors declared private are strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class.Protected access modifier
The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods and constructors declared protected in a superclass can be accessed only 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.Default access modifier
Java provides a default specifier which is used when no access modifier is present. Any class, field, method or constructor that has no declared access modifier is accessible only by classes in the same package. The default modifier is not used for fields and methods within an interface.Below is a program to demonstrate the use of public, private, protected and default access modifiers while accessing fields and methods. The output of each of these java files depict the Java access specifiers.
Next : Introduction to java classes