What are access modifiers in java explain with examples
In Java, access modifiers are keywords used to set the accessibility or visibility of classes, methods, variables, or constructors. They control the level of access that other classes have to these components.
There are four types of access modifiers in Java:
Modifier | Description |
Public | declarations are visible everywhere |
Protected | declarations are visible within the package or all subclasses |
Private | declarations are visible within the class only |
Default | declarations are visible only within the package (package private) |
1. public
: Members declared as public
are accessible from any class. They have the widest scope among all access modifiers.
Example:
/*
* Author: Zameer Ali
* */
public class MyClass {
public int publicVar;
public void publicMethod() {
// Code here
}
}
2. protected
: Members declared as protected
are accessible within the same package and subclasses, even if they are in different packages.
Example:
/*
* Author: Zameer Ali
* */
public class MyClass {
protected int protectedVar;
protected void protectedMethod() {
// Code here
}
}
3. default
(no modifier): Members with no explicit modifier (also known as package-private) are accessible within the same package but not from outside the package.
Example:
/*
* Author: Zameer Ali
* */
class MyClass {
int defaultVar;
void defaultMethod() {
// Code here
}
}
4. private
: Members declared as private
are accessible only within the same class. They have the narrowest scope among all access modifiers.
Example:
/*
* Author: Zameer Ali
* */
public class MyClass {
private int privateVar;
private void privateMethod() {
// Code here
}
}
Usage Examples:
/*
* Author: Zameer Ali
* */
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.publicVar = 10; // Accessing public variable
obj.publicMethod(); // Accessing public method
obj.protectedVar = 20; // Accessing protected variable
obj.protectedMethod(); // Accessing protected method
obj.defaultVar = 30; // Accessing default variable (within the same package)
obj.defaultMethod(); // Accessing default method (within the same package)
obj.privateVar = 40; // Error: privateVar has private access in MyClass
obj.privateMethod(); // Error: privateMethod() has private access in MyClass
}
}
In this example, publicVar
and publicMethod()
can be accessed from anywhere because they are declared as public
. protectedVar
and protectedMethod()
are accessible because they are in the same package. defaultVar
and defaultMethod()
are accessible because they are in the same package and have default access. privateVar
and privateMethod()
are not accessible outside the MyClass
because they are private.