Java Modifiers are used to define access to various Java classes and objects, Java methods, and Java constructors. An access modifier restricts the access of a class, constructor, data member and method in another class. In java we have four access modifiers:
default
private
protected
public
1)default access modifier
When we do not mention any access modifier, it is called default access modifier. The scope of this modifier is limited to the package only. This means that if we have a class with the default access modifier in a package, only those classes that are in this package can access this class.
package p1;
public class Addition
{
int addTwoNumbers(int a, int b)
{
return a+b;
}
}
package p2;
import p1.*;
public class Main
{
public static void main(String args[])
{
Addition obj = new Addition();
obj.addTwoNumbers(10, 21);
}
}
2)private access modifier
The scope of private modifier is limited to the class only.
Private Data members and methods are only accessible within the class.
Classes and Interfaces cannot be declared as private.
If a class has private constructor then you cannot create the object of that class from outside of the class.
class ABC
{
private double num = 100;
private int square(int a)
{
return a*a;
}
}
public class PP
{
public static void main(String args[])
{
ABC obj = new ABC();
System.out.println(obj.num);
System.out.println(obj.square(10));
}
}
3)protected access modifier
protected data member and methods are only accessible by the classes of the same package and the subclasses present in a package through inheritance only. The protected access modifier can be applied to the data member, method and constructor. It can’t be applied to the class.
package A1;
public class Addition1
{
protected int add(int a, int b)
{
return a+b;
}
}
package B1;
import A1.*;
class Main1 extends Addition1
{
public static void main(String args[])
{
Addition1 obj = new Addition1 ();
System.out.println(obj.add(5, 7));
}
}
4)public access modifier
The members, methods and classes that are declared public can be accessed from anywhere. This modifier doesn’t put any restriction on the access.