Java Tutorial

Basic Concepts

Object Oriented Concepts

Coming Tutorials

>Home>Java Tutorial>Access Modifiers in Java

Java Tutorial

Basic Concepts

Object Oriented Concepts

Coming Tutorials



Public, Protected, Private Access Modifiers / Keywords in Java

The accessibility or availability of fields, methods, constructors, class, etc. is called scope of that component.

In java there are 4 types of scopes available, those are listed below.

  1. Within the same class only

  2. Within the same package only

  3. Inside the sub / child class

  4. Global / Anywhere

The scope of the components by default is within the same package.Therefore any non local fields, constructors, methods of a class can be accessed within the same class and inside the classes residing in the same package.

You can change or modify this scope using three access modifiers they are.

  1. Private

  2. Protected

  3. Public


The private Modifier:

If you want to restrict the access of a field, method or a constructor to the same class only then use private access modifier. If we make any element private then it cannot be accessed from outside the class.

The private modifier is not allowed for outer class, for example.

private class Test

{

}

D:\>javac Test.java //Compile time exception.

The private modifier is not allowed for abstract methods, for example.

private abstract class Test

{

}

D:\>javac Test.java //compile time exception


The protected Modifier:

If you want to restrict the use of a element within the same package and sub classes from same or different classes then use protected access modifier. The protected elements can be accessed from child classes and from classes residing in same package.


The public Modifier:

If you declare any element as public then it can be accessed from anywhere.

Note: If you did not mention any access modifiers then by default it will be default access modifier. You do not need to mention default modifier.

The following table shows the scopes and access modifiers.

Modifier Within the same class Within the same package Inside the sub class of diff. Package. Global / Anywhere
private Yes No No No
default Yes Yes No No
protected Yes Yes yes No
public Yes Yes Yes Yes

Share the article to help your friends