Public - can be accessed in any Class in any package
default - also known as package public. can be accessed in any class of same package.
private can be only accessed in the same class
protected - can be only accessed in the same package AS WELL AS SUBCLASSES in DIFFERENT PACKAGES.
Rule is to define Class or Interface as public or default and members are private or public.Class can de declared default by removing the keyword public from infront of it.
But we cannot define a Class as private and then try to define members as public . this will throw an error.
Another thing to note is the scenario for inner class. Any variable declared private in a outer class can be accessed directly i.e without using a getter in inner class.
And in same way variable declared private In inner class can be accessed directly using inner class object in outer class.
Class Outer{
private variable A;
public printB(){
Inner I = new Inner();
System.out.println(“The value of inner class variable B accessible here is”+I.B);
}
Class Inner{
private variable B;
//Inner constructor
Inner(){
System.out.println(“The value of outer class variable A accessible here is”+A);
}
}
}