Access modifiers are a set of keywords that determines the visibility and accessibility of classes, methods, and fields. Java provides four access levels correspond to four access modifiers.

  • public
  • protected
  • default
  • private

Public access modifier

Same class accessTrue
Same package subclass accessTrue
Same package non-subclass accessTrue
Different package subclass accessTrue
Different package non-subclass accessTrue
Key word: public
package p1;
 
public class A {
	public void display(){
		System.out.println("Hi there");
	}
}
package p2;
import package p1.*;
 
class B {
	public static void main(String args[]) {
		A obj = new A();
		obj.display();
	}
}
Hi there

Protected access modifier

Same class accessTrue
Same package subclass accessTrue
Same package non-subclass accessTrue
Different package subclass accessTrue
Different package non-subclass accessFalse
Keyword: protected
package p1;
 
public class A {
	protected void display(){
		System.out.println("Hi there");
	}
}
package p2;
import p1.*; 
 
class B extends A {
    public static void main(String args[]) {
        B obj = new B();
        obj.display();
    }
}
Hi there

Default access modifier

Same class accessTrue
Same package subclass accessTrue
Same package non-subclass accessTrue
Different package subclass accessFalse
Different package non-subclass accessFalse
package p1;
 
class A {
	void display(){
		System.out.println("Hi there");
	}
}
package p2; 
import p1.*; 
 
class B { 
    public static void main(String args[]) { 
	    // Error when accessing class from another package
        A obj = new A(); 
        obj.display(); 
    } 
}
Compile time error

Private access modifier

Same class accessTrue
Same package subclass accessFalse
Same package non-subclass accessFalse
Different package subclass accessFalse
Different package non-subclass accessFalse
Keyword: private
package p1;
 
class A {
    private void display() {
        System.out.println("Hi there");
    }
}
 
class B {
    public static void main(String args[]) {
        A obj = new A();
        
        // cannot access private method
        obj.display();
    }
}
error: display() has private access in A  
        obj.display();

Back to parent page: Java Standard Edition (Java SE) and Java Programming

Web_and_App_DevelopmentProgramming_LanguagesJavaAccess_Modifier

Reference