When using Java, often encounter four kinds of modifiers, namely public,protected, default (no modifier), private, here write down their differences public: In-Package outside the package access
Protected: In-package access, out-of-package only subclass access
Default: Any access within the package
Private: In-class access only
Explain in code
1 PackageP1;2 Import Staticjava.lang.system.*;3 4 Public classA {5 Public intM1 = 1;6 protected intM2 = 2;7 intM3 = 3;8 Private intM4 = 4;9 Ten Public voidF1 () { OneOut.println ("F1"); A } - protected voidF2 () { -Out.println ("F2"); the } - voidF3 () { -Out.println ("F3"); - } + Private voidf4 () { -Out.println ("F4"); + } A at voidDemo () { - OUT.PRINTLN (M1); - out.println (m2); - out.println (m3); - Out.println (M4); - in F1 (); F2 (); F3 (); F4 () ; - tob b =NewB (); + } - the Public Static voidMain (string[] args) { * NewA (). Demo (); $ }Panax Notoginseng } - the classB { + PublicB () { AOut.println ("Class B"); the } +}
P1. A
1 PackageP1;2 Import Staticjava.lang.system.*;3 4 Public classC {5 voidDemo () {6A A =NewA ();7 out.println (A.M1);8 out.println (a.m2);9 out.println (a.m3);Ten //out.println (A.M4); One A a.f1 (); A.f2 (); a.f3 (); - //a.f4 (); - the //the default class can be used within the same package -b b =NewB (); - } - + Public Static voidMain (string[] args) { - NewC (). Demo (); + } A}
P1. C
PackageP2;Importp1.*;Import Staticjava.lang.system.*; Public classD {voidDemo () {A A=NewA (); Out.println (A.M1); //none of the following can be accessed//out.println (A.M2); //out.println (A.M3); //out.println (A.M4);a.f1 (); //none of the following can be called//A.f2 (); //a.f3 (); //a.f4 (); //default classes cannot be used within other packages//b b = new B (); } Public Static voidMain (string[] args) {NewD (). Demo (); E.main (args); }}classEextendsa{//subclasses of a voidDemo () {OUT.PRINTLN (M1); Out.println (Super. M1); Out.println (NewA (). M1); Out.println (m2); Out.println (Super. m2); //out.println (New A (). m2);//failed//out.println (A.M3); //out.println (A.M4);F1 (); F2 (); Super. F2 (); //new A (). F2 ();//failed//a.f3 (); //a.f4 (); //default classes cannot be used within other packages//b b = new B (); } Public Static voidMain (string[] args) {NewE (). Demo (); }}
P1. D
[Thinking in Java] modifier public,protected, default, private