Access Modifiers in Java
Access Modifiers in Java
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:
1 private
2 default
3 protected
4 public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile,
transient etc. Here, we will learn access modifiers.
class A{
A obj=new A();
}
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class
from outside the class. For example:
class A{
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
}
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
//save by A.java
package pack;
public class A{
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
obj.msg();
}
Output:Hello
package pack;
public class A{
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
obj.msg();
}
Output:Hello
Private Y N N N
Default Y Y N N
Protecte Y Y Y N
d
Public Y Y Y Y
class A{
}
The default modifier is more restrictive than protected. That is why there is compile
time error.