Access Modifiers in Java
→ Access modifiers are used to set the accessibility of classes, interfaces, variables, methods, constructors, data members, and the setter methods.
Types of Access Modifiers
There are two types of access modifiers
Understanding all java access modifiers
Let's understand the access modifiers by a simple table.
1) public access modifier
→ The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
2) Private access modifier
→ Private access modifier they cannot be accessed outside of the class When declared variables and methods are private .
→ The private access modifier is accessible only within class.
Compile time Error
3) Protected access modifier
→ Protected Access Modifier can access within the same package as well as from subclasses, when methods and data members are declared protected
→ Protected Access Modifier can be applied on the data member, method and constructor. It can't be applied on the class.
Example 1 :-
Example 2 :-
4) Default access modifier
→ If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within package. It cannot be accessed from outside the package.
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the package.
Next TopicEncapsulation in Java