在使用Java时,常常会遇到四种修饰符,即public,protected,默认(没有修饰符),private,这里写下它们的区别
public :包内包外任意访问
protected :包内任意访问,包外仅子类访问
默认 :包内任意访问
private :仅类内访问
用代码解释
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 a = new A(); 7 out.println(a.m1); 8 out.println(a.m2); 9 out.println(a.m3);10 //out.println(a.m4);11 12 a.f1();a.f2();a.f3();13 //a.f4();14 15 //默认类可以在同一个包内使用16 B b = new B();17 }18 19 public static void main(String[] args) {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 a = new A(); 8 out.println(a.m1); 9 //以下都无法访问10 //out.println(a.m2);11 //out.println(a.m3);12 //out.println(a.m4);13 14 a.f1();15 //以下都无法调用16 //a.f2();17 //a.f3();18 //a.f4();19 20 //默认类不能在其它包内使用21 //B b = new B();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{//A的子类31 void demo() {32 out.println(m1);33 out.println(super.m1);34 out.println(new A().m1);35 36 out.println(m2);37 out.println(super.m2);38 //out.println(new A().m2);//失败39 //out.println(a.m3);40 //out.println(a.m4);41 42 f1();43 f2();44 super.f2();45 //new A().f2();//失败46 //a.f3();47 //a.f4();48 49 //默认类不能在其它包内使用50 //B b = new B();51 }52 53 public static void main(String[] args) {54 new E().demo();55 }56 }