Access Modifiers in JAVA
The access Specifier in Java specifies the accessibility or scope of a field, method, constructor, or class.We can change the access level of fields, constructors, methods, and class by applying the access specifier on it.
- Default – No keyword required
- Private
- Protected
- Public
Access Specifier
|
Within Class
|
Within Package
|
Outside Package by Subclass only
|
Outside Package
|
Private
|
Yes
|
No
|
No
|
No
|
Default
|
Yes
|
Yes
|
No
|
No
|
Protected
|
Yes
|
Yes
|
Yes
|
No
|
Public
|
Yes
|
Yes
|
Yes
|
Yes
|
Private
class exofprivate{
private int a=40;
private void fun1(){
System.out.println("Hello java");}
}
public
class Pairosoft{
public static void main(String[] args) {
exofprivate obj=new exofprivate();
System.out.println(obj.a);
//Compile Time Error
obj.fun1(); //Compile Time Error
}
}
|
Default
The default modifier is accessible only within package. It cannot be accessed from outside the package.
Example:
//save by c1.java
package pack1;
class c1{
void fun1()
{
System.out.println("Hello");
}
}
|
//save by c2.java
package pack2;
import pack1.*; //import package(pack1)
class c2{
public static void main(String args[]){
c1 obj = new c1();//Compile Time Error
obj.fun1();//Compile Time Error
}
}
|
Protected
The protected access modifier is accessible within package and outside the package but through inheritance only.
Example:
//save by c1.java
package pack1;
public class c1{
protected void fun1()
{
System.out.println("Hello Friends"); }
}
|
//save by c2.java
package mypack;
import pack1.*;
class c2 extends c1{
public
static void main(String args[]){
c2 obj =
new c2();
obj.fun1();
}
}
|
Output:
Hello
Friends
|
In this example, we have created the two packages pack1 and pack2. The c1 class of pack1 package is public, so can be accessed from outside the package. But fun1 method of this package is declared as protected, so it can be accessed from outside the class only through inheritance.
Public
The public access modifier is accessible everywhere.
Example:
//save by c1.java
package pack1;
public class c1{
public void fun1()
{ System.out.println("Hello");}
}
|
|
Output:
|
0 Comments