Access modifiers in Java

Beknazar
2 min readApr 14, 2021

--

Access modifiers are used to control access for variables, methods, and sometimes inner classes.

There are 4 access modifiers available:

public — accessible from everywhere. If we mark it as public it will be accessible from everywhere.

protected — accessible within the same package and child classes.

default — if we don't put anything it’s the default access modifier. It’s accessible within the same package only.

private — accessible within the same class only.

Let’s take a look at the examples with methods:

  • Main and Practice are in the same package.
  • We can use public, protected, and default methods in Practice class, but we have compiler error for our private method. Because it is accessible within the same class only.

The access modifiers are needed to encapsulate our code and are used with one of the OOP concepts — encapsulation.

--

--

Beknazar
Beknazar

No responses yet