There are four types of access modifiers defined in Java. They are: public, decorated with the public keyword, visible to all classes; Protected with the protected keyword, visible to classes and all subclasses within the same package; Private is decorated with the private keyword and is visible only within the same class; There is also the default (default not explicitly annotated), which is only visible within the same package and does not use any modifiers. A parent class can only be accessed outside the package if it is defined as a public class, otherwise a member can only be accessed by the class inside the package, regardless of its access rights.
In the same package (same for methods and fields)
package package1; /** * public class A {int A; Public int b; // public public protected int c; // protected private int d; // Private voidtest() { System.out.print(a); // Access the default system.out.print (b); Public system.out.print (c); // Access protected system.out.print (d); Private}} package package1; /** * class B {A ca = new A(); voidtest() { System.out.print(ca.a); // Access the default system.out.print (ca.b); Public system.out.print (ca.c); // Access protected // system.out.print (ca.d); Private}} package package1; /** * extends A {void */ class C extends A {void */test() { System.out.print(a); // Access the default system.out.print (b); Public system.out.print (c); // Access protected // system.out.print (d); Not accessible to private}}Copy the code
Not in the same package (same for methods and fields)
package package1; /** * public class A {int A; Public int b; // public public protected int c; // protected private int d; // Private voidtest() { System.out.print(a); // Access the default system.out.print (b); Public system.out.print (c); // Access protected system.out.print (d); Private}} package package2; /** * class B {A ca = new A(); voidtest() { // System.out.print(ca.a); // Can not access the default system.out.print (ca.b); Public // system.out.print (ca.c); // Protected // system.out.print (ca.d); Private}} package package3; /** * extends A {void */ class C extends A {void */test() { // System.out.print(a); // Can not access the default system.out.print (b); Public system.out.print (c); // Access protected // system.out.print (d); Not accessible to private}}Copy the code