MJ#25: Access Modifiers in Java

n Java, access modifiers are keywords that define the visibility and accessibility of classes, methods, and variables. They control which other classes can access a particular class, method, or variable. There are four main access modifiers in Java:

  1. Default (Package-Private):
    • If no access modifier is specified, the default access level is package-private. This means that the class, method, or variable is accessible within the same package but not outside of it.
class Example {

int x; // Package-private variable
void method() { // Package-private method
// ...
}
}

Public:

  • The public access modifier makes the class, method, or variable accessible from anywhere. This includes other packages.
public class PublicExample {

public int y; // Public variable
public void publicMethod() { // Public method
// ...
}
}

Private:

  • The private access modifier restricts the visibility to only within the class where it is declared. It is not accessible from outside the class, including subclasses.
public class MyClass {

private int z; // Private variable
private void privateMethod() { // Private method
// ...
}
}

Protected:

  • The protected access modifier allows access within the same package, as well as in subclasses (even if they are in different packages).
package com.example;


public class ParentClass {
protected int protectedVariable; // Protected variable
protected void protectedMethod() { // Protected method
// ...
}
}
package com.example.subpackage;


public class ChildClass extends ParentClass {
void accessProtected() {
protectedVariable = 10; // Accessing protected variable from the superclass
protectedMethod(); // Accessing protected method from the superclass
}
}

Here’s a summary of the access permissions for each access modifier:

Access ModifierWithin ClassWithin PackageOutside Package (Subclass)Outside Package (Non-subclass)
DefaultYesYesNoNo
PublicYesYesYesYes
PrivateYesNoNoNo
ProtectedYesYesYesNo

It’s important to choose the appropriate access level based on the design and encapsulation principles to ensure proper data hiding and abstraction in your Java programs.

Leave a comment