[Thinking in Java] modifier public, protected, default, private, thinkingprotected
When using Java, four modifiers, public, protected, default (no modifier), and private, are often encountered. The differences between them are written here.
Public: any access outside the package
Protected: any access in the package, only sub-class access outside the package
Default: any access in the package
Private: class-based access only
Use code to explain
1 package p1; 2 import static java.lang.System.*; 3 4 public class A { 5 public int m1 = 1; 6 protected int m2 = 2; 7 int m3 = 3; 8 private int m4 = 4; 9 10 public void f1() {11 out.println("f1");12 }13 protected void f2() {14 out.println("f2");15 }16 void f3() {17 out.println("f3");18 }19 private void f4() {20 out.println("f4");21 }22 23 void demo() {24 out.println(m1);25 out.println(m2);26 out.println(m3);27 out.println(m4);28 29 f1();f2();f3();f4();30 31 B b = new B();32 }33 34 public static void main(String[] args) {35 new A().demo();36 }37 }38 39 class B {40 public B() {41 out.println("class B");42 }43 }
1 package p1; 2 import static java. lang. system. *; 3 4 public class C {5 void demo () {6 A = new a (); 7 out. println (. m1); 8 out. println (. m2); 9 out. println (. m3); 10 // out. println (. m4); 11 12. f1 ();. f2 ();. f3 (); 13 //. f4 (); 14 15 // default class can use 16 B B = new B (); 17} 18 19 public static void main (String [] args) in the same package) {20 new C (). demo (); 21} 22}
1 package p2; 2 import p1. *; 3 import static java. lang. system. *; 4 5 public class D {6 void demo () {7 A = new a (); 8 out. println (. m1); 9 // cannot access 10 // out. println (. m2); 11 // out. println (. m3); 12 // out. println (. m4); 13 14. f1 (); 15 // cannot call 16 //. f2 (); 17 //. f3 (); 18 //. f4 (); 19 20 // The default class cannot use 21 // B B = new B () in other packages (); 22} 23 24 public static void main (String [] args) {25 new D (). demo (); 26 E. main (args); 27} 28} 29 30 class E extends A {// subclass of A 31 void demo () {32 out. println (m1); 33 out. println (super. m1); 34 out. println (new (). m1); 35 36 out. println (m2); 37 out. println (super. m2); 38 // out. println (new (). m2); // failed 39 // out. println (. m3); 40 // out. println (. m4); 41 42 f1 (); 43 f2 (); 44 super. f2 (); 45 // new (). f2 (); // failure 46 //. f3 (); 47 //. f4 (); 48 49 // The default class cannot use 50 // B B = new B () in other packages (); 51} 52 53 public static void main (String [] args) {54 new E (). demo (); 55} 56}