Access Modifiers or Specifiers with an Example

In this class, We discuss Access Modifiers or Specifiers with an Example.

The reader should have prior knowledge of packages in Java. Click Here.

There are four access modifiers in Java.

1) Public

2) Private

3) Protected

4) No modifier

We take an example and understand the access modifier.

The below diagram shows an example.

class A

{

private int p;

void add()

{

System.out.println(p);

}

}

Class B extends A

{

void m2()

{

System.out.println(p);

}

}

In the above example, variable “p” is private.

The private variables can not be accessed in the inherited class.

In class “B,” variable “p” can not be accessed.

Giving a variable or a method accessing limit is called an access modifier or specifier,

The below table shows the complete accessing limits of all the modifiers.

Here “no modifier” means not writing any access modifier before a variable or method.

We take examples for all levels and understand the concept.

Private variables can be accessed only inside a class.

The below diagram shows the example.

The same package sub-class example is shown below.

The same package nonsubclass example is shown below.

Different package sub-class examples are shown below.

In the above example, no modifier variables are not accessed and protected variables can be accessed.

Different package non-sub class examples are shown below.

The protected variables cannot be accessed in different packages non-sub classes.

Only public variables are allowed access.