private visibility allows a variable to only be accessed by its class. They are often used in conjunction with public getters and setters.
classSomeClass {privateint variable;publicintgetVariable() {return variable; }publicvoidsetVariable(int variable) {this.variable= variable; }}publicclassSomeOtherClass {publicstaticvoidmain(String[] args) {SomeClass sc =newSomeClass();// These statement won't compile because SomeClass#variable is private:sc.variable=7;System.out.println(sc.variable);// Instead, you should use the public getter and setter:sc.setVariable(7);System.out.println(sc.getVariable()); }}
Protected Visibility
Protected visibility causes means that this member is visible to its package, along with any of its subclasses.
packagecom.stackexchange.docs;publicclassMyClass {protectedint variable; // This is the variable that we are trying to accesspublicMyClass() { variable =2; };}
Public Visibility
Visible to the class, package, and subclass
publicclassTest{publicint number =2;publicTest(){ }}publicclassOther{publicstaticvoidmain(String[] args){Test t =newTest();System.out.println(t.number); }}