Java has four access control modifiers.
In order to compare the differences with code, first create two packages, area1 and area2; five classes are Person, PersonDemo, PersonSon, PersonTest, and OutPerson.
Then put Person, PersonDemo, PersonSon under area1.
PersonTest and OutPerson are placed under area2 package.
Examples of four access control modifiers in the same category:
package area1;public class Person { public String _public="public variable"; //Define a public variable private String _private="private variable"; //Define a private variable protected String _protected="protected variable"; //Define a protected variable String _default="default"; //Define a variable public void _pub(){ //Create a public method System.out.println(_public); } private void _pri(){ //Create a private method System.out.println(_private); } protected void _pro(){ //Create a protection method System.out.println(_protected); } void _def(){ //Create the default method System.out.println(_default); } public static void main(String[] args){ Person p=new Person(); //Create the object p._pub(); //Calend the method p._pri(); p._pro(); p._def(); } }Examples of code of four access control modifiers under different classes (excluding subclasses) in the same package:
package area1;public class PersonDemo { public static void main(String[] args){ Person p=new Person(); //Create the object of the Person class p._pub(); p._pri(); //Report an error p._pro(); p._def(); } }Examples of the code of four access control modifiers under the same bun subclass:
package area1;public class PersonSon extends Person{ //Subclass PersonSon inherits the parent class Person public static void main(String[] args){ PersonSon son=new PersonSon(); //Subclass creates object son._pub(); son._pro(); son._def(); son._pri(); //Reports error Person father=new Person(); //Preparate class creates object father._def(); father._pub(); father._def(); father._pri(); //Reports error} }Examples of code of four access control modifiers under different classes (excluding subclasses) in the same package:
package area2;import area1.Person; //Reference the Person class public class PersonTest { public static void main(String[] args){ Person p=new Person(); //Person class creates object p._pub(); p._pro(); //Reports error p._pri(); //Reports error p._def(); //Reports error} }Examples of the code of four access control modifiers under the same bun subclass:
package area2;import area1.Person; //Reference the Person class under area1 package public class OutPerson extends Person{ //Subclass inherits the parent class public static void main(String[] args){ OutPerson out=new OutPerson(); //Subclass creates an object out._pub(); out._pro(); out._pri(); //Reports an error out._def(); //Reports an error} }Note: Compare with the chart carefully!