-
Notifications
You must be signed in to change notification settings - Fork 13
Access Modifier
Modifier | Class | Package | Subclass | World |
---|---|---|---|---|
public |
Yes | Yes | Yes | Yes |
protected |
Yes | Yes | Yes | No |
no modifier | Yes | Yes | No | No |
private |
Yes | No | No | No |
There are FOUR (4) access level modifiers. Each of these modifiers provides a different level of access control and can be applied to:
- classes
- methods
- constructors
- variables.
Here's a list of the modifiers with their accessibility:
-
Default (no modifier): If no access modifier is specified for a class member, Java uses the default access level. Members with default access can be accessed by other members in the same package, but not from outside the package.
-
Public: Members marked as public can be accessed from any other class in the Java program, regardless of the package the class is in.
-
Protected: Members with protected access can be accessed by classes in the same package and by subclasses even if they are in different packages.
-
Private: Members with private access can be accessed only within their own class.
class DefaultClass {
void defaultMethod() {
// Can be accessed from any other class
}
}
public class PublicClass {
public void publicMethod() {
// Can be accessed from any other class
}
}
public class PrivateExample {
private int privateVariable = 10;
private void privateMethod() {
// Can only be accessed within PrivateExample class
}
}
public class ProtectedExample {
protected int protectedVariable = 20;
protected void protectedMethod() {
// Can be accessed within the same package
// and in subclasses even if they are in different packages
}
}