Public
Has the maximum access rights. all classes are accessible.
Protected
is primarily used to protect subclasses. itself, subclasses, and classes in the same package can access
Default
Without modifiers. Sometimes referred to as friendly, it is designed for access to this package. can be accessed in the same package.
Private
Access is limited to the inside of the class, and is an embodiment of encapsulation. can only be accessed by themselves
|
Class Internal |
Sub-class interior (this package) |
Other classes (this package) |
Intra-subclass (external package) |
Other classes (external packages) |
Public |
O |
O |
O |
O |
O |
Protected |
O |
O |
O |
O |
X |
Default |
O |
O |
O |
X |
X |
Private |
O |
X |
X |
X |
X |
Sample code
Package apkg
Parenta.java
Packageapkg; Public classParenta { PublicString publicvariable = "public"; protectedString protectedvariable = "protected"; String variable= "Default"; PrivateString privatevariable = "Privater"; Public voidShow () {System.out.println ( This. publicvariable); System.out.println ( This. protectedvariable); System.out.println ( This. variable); System.out.println ( This. privatevariable); } Public Static voidMain (string[] args) {Parenta apkg=NewParenta (); Apkg.show (); }}
Sona.java
Packageapkg; Public classSonAextendsParenta { Public voidShow () {System.out.println ( This. publicvariable); System.out.println ( This. protectedvariable); System.out.println ( This. variable); //System.out.println (this.privatevariable);//Cannot access }}
Unclea.java
package apkg; import apkg. Parenta; public class Unclea { public void show () {Parenta apkg = new Parenta (); System.out.println (apkg.publicvariable); System.out.println (apkg.protectedvariable); System.out.println (apkg.variable); // system.out.println ( apkg.privatevariable); // cannot access }}
Package bpkg
Sonb.java
Packagebpkg;Importapkg. Parenta; Public classSonbextendsParenta { Public voidShow () {System.out.println ( This. publicvariable); System.out.println ( This. protectedvariable); //System.out.println (this.variable);//Cannot access//System.out.println (this.privatevariable);//Cannot access }}
Uncleb.java
Packagebpkg;Importapkg. Parenta; Public classUncleb { Public voidShow () {Parenta apkg=NewParenta (); System.out.println (apkg.publicvariable); //System.out.println (apkg.protectedvariable);//Cannot access//System.out.println (apkg.variable);//Cannot access//System.out.println (apkg.privatevariable);//Cannot access }}
Java Modifier public,protected,default,private access rights