5. Access control in Java
5. Access control in Java
Access control in Java is a mechanism that restricts access to classes, methods, and variables to
ensure security. Java provides four levels of access control using access modifiers:
private ✅ Yes ❌ No ❌ No ❌ No
1. private
class Example {
private int data = 10; // Private variable
Note: The data and display() method are only accessible within the Example class.
class Example {
int data = 10; // Default variable
3. protected
A package is a namespace that organizes related classes and interfaces. It helps prevent naming
conflicts by providing a unique namespace for classes, interfaces, and other components. This is
particularly useful in large projects(Emp class in ProjectA package and Emp class in package
ProjectB). We can reference both Emp classes using fully qualified names like
projectA.Employee empA = new projectA.Employee();
Example:
package package1;
public class Parent {
protected int data = 20; // Protected variable
4. public
package mypackage;