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.
Within the same class only
Within the same package only
Inside the sub / child class
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.
Private
Protected
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 |