Java access modifiers control the visibility of classes, variables, methods, and other members of a Java program.
What are access modifiers in Java?
Access modifiers are used to specify the scope of access of the member variable and methods of a class from a different class or package. The accessibility scope varies based on the modifiers you use. There are four access modifiers in Java –
- Default
- Private
- Protected
- Public
Access Modifier Table
Access Modifier | Default | Private | Protected | Public |
---|---|---|---|---|
Same Class | Y | Y | Y | Y |
Same Package Subclass | Y | N | Y | Y |
Same Package Non-Subclass | Y | N | Y | Y |
Different Package Subclass | N | N | Y | Y |
Different Package Non-Subclass | N | N | N | Y |
Description
- You can access the Default, Private, Protected, and Public variables within the same class.
- You can access the Default, Protected, and Public but not the private variables in the Same Package Subclass.
- You can access the Default, Protected, and Public but not the private variables in the Same Package Non-Subclass.
- You can access the Protected and Public variables but not the Default and Private variables in the Different Package Subclass.
- You can access the Public variables but not the Default and Private and Protected variables in the Different Package Non-Subclass.
Explanation Video
Feel free to share your viewpoints on this topic in the comments section below 🙂