DEV Community

Deva I
Deva I

Posted on

Access Modifier. When to Use and When Not to Use for class, method, variable and constructors.

Definition :

✓ Access modifiers in Java are keywords that set the visibility and accessibility of classes, constructors, methods, and variables.

The Four Access Modifiers

1.Private :

✓ The code is accessible only within the same class.

✓ It cannot be accessed by any outside class, even the same package.

2.Default (Package level access Modifier) :

✓ This not have any specify keyword,Java automatically applies the default access modifier.(No keyword)

✓ Components are accessible only within the same package.

✓ Cannot access the different package, even they have the child class.

3.Protected :

✓ Accessible within the same package and by subclasses.

✓ Also access the different package sub class(child class).

✓ Cannot access the different package non-sub class only.

4.Public :

✓ Components are accessible from anywhere in the program.

1. Access Modifiers for Classes

Only public and default can be used for top-level classes.

  • public- Accessed anywhere in the program.

  • default- Only inside the same package can use it.

  • protected and private cannot used in top level classes, they only used in nested classes.

2. Access Modifiers for Variables

Variables can use all four modifiers.

  • public- Accessed anywhere in the program.

  • protected- Accessed by same class, same package, different package child class. cannot access different package non-child class.

  • default- Accessible only within the same package.Different package can't access it even they have child class.

  • private- Only accessible within the same class.

3. Access Modifiers for Methods

Methods can support all four modifiers.

  • public- Accessed anywhere in the program.

  • protected- Accessed by same class, same package, different package child class. cannot access different package non-child class.

  • default- Accessible only within the same package.Different package can't access it even they have child class.

  • private- Only accessible within the same class.

4. Access Modifiers for Constructors

Constructors can also use all four modifiers.

  • public- When any class from any package should be able to create objects.

  • protected- Use when object creation should be limited to Same package, Subclasses in other packages.

  • default- Only classes in the same package can create objects.

  • private- Use when you don't want anyone outside the class to create objects directly.

Top comments (0)