There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class.
There are 4 types of java access modifiers:
- private
- default
- protected
- public
private access modifier
If you make any class constructor private, you cannot create the instance of that class from outside the class.
class vipul{
private vipul()
{
}//private constructor
void msg()
{
System.out.println("Hello java");
}
}
public class Simple
{
public static void main(String args[])
{
vipul obj=new vipul();//Compile Time Error
}
}
default access modifier
we have created two packages pack and mpack. We are accessing the VIPUL class from outside its package, since VIPUL class is not public, so it cannot be accessed from outside the package.
//save by VIPUL.java
package pack;
class VIPUL
{
void msg()
{
System.out.println("Hello");
}
}
//save by Agravat.java
package mpack;
import pack.*;
class Agravat
{
public static void main(String args[]){
VIPUL obj = new VIPUL();//Compile Time Error obj.msg();//Compile Time Error
}
}
the scope of class VIPUL and its method msg() is default so it cannot be accessed from outside the package.
protected access modifier
The protected access modifier is accessible within package and outside the package but through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.
//save by VIPUL.java
package pack;
public class VIPUL
{
protected void msg()
{
System.out.println("Hello");
}
}
we have created the two packages pack and mpack. The VIPUL class of pack package is public, so can be accessed from outside the package. But msg() method of this package is declared as protected, so it can be accessed from outside the class only through inheritance.
//save by Agravt.java
package mpack;
import pack.*;
class Agravat extends VIPUL
{
public static void main(String args[])
{
Agravat obj = new Agravat();
obj.msg();
}
}
print "Hello"..........