1.java修饰符的访问权限
访问权限 类 包 子类 其他包
public √ √ √ √
protected √ √ √ ×
default √ √ × ×
private √ × × ×
主要为了看protected能在子类访问的问题:因为发现在不同包中,子类中并不能访问父类protected修饰的方法和属性。
2.protected修饰方法在类所在包以外的包,只能通过子类继承访问;且子类只能访问自己继承自父类的protected变量和方法,而不能访问父类的protected变量和方法。
3.类(非内部类)可用public和default两种权限修饰符修饰,且默认为default;
4.局部变量只能用用default权限修饰符修饰(默认包修饰符);
===============================================================
下面为以上结论的测试代码:
以下测试代码的Class结构如下:
com.software.chensan Test01.javacom.software.chensan Test02.java
com.software Test03.java
package com.software.chensan; public class Test01 { public String publicAttr = "publicAttr"; protected String protectedAttr = "protectedAttr"; String defaultAttr = "defaultAttr"; private String privateAttr = "privateAttr"; public void publicM() { System.out.println("test01 public method"); } protected void protectedM() { System.out.println("test01 protected method"); } void defaultM() { System.out.println("test01 default method"); privateM(); } private void privateM() { System.out.println(privateAttr); System.out.println("test01 private method"); } }
package com.software.chensan; public class Test02 { public static void main(String[] args) { Test01 test1 = new Test01(); System.out.println(test1.publicAttr); System.out.println(test1.protectedAttr); System.out.println(test1.defaultAttr); System.out.println(test1.privateAttr);//The field Test01.privateAttr is not visible System.out.println(test1.undefinedAttr);//undefinedAttr cannot be resolved or is not a field test1.publicM(); test1.protectedM(); test1.defaultM(); test1.privateM();//The method privateM() from the type Test01 is not visible test1.undefinedM();//The method undefinedM() is undefined for the type Test01 } }
package com.software; import com.software.chensan.Test01; public class Test03 extends Test01 { public static void main(String[] args) { Test01 test1 = new Test01(); System.out.println(test1.protectedAttr);//The field Test01.protectedAttr is not visible test1.protectedM();//The method protectedM() from the type Test01 is not visible Test03 test3 = new Test03(); System.out.println(test3.protectedAttr); test3.protectedM(); } }
Test02与Test01在同一个包中,protected和default的访问权限是一样的(不论是否继承)。
Test03与Test01不在同一个包中,不能访问父类Test01中的protected变量和方法,只能访问自己继承自父类的变量和方法。
protected的语义,参考:http://blog.csdn.net/hongyuan19/article/details/1946636
3.类(非内部类)的修饰符只能为public和default,且默认为default
包结构如下:
com.chensan.Test1;
com.chensan.test.Test2;
public class Test1 { public void method1() { System.out.println("Test1 method1"); } } public class Test2 { public static void main(String[] args) { Test1 test1 = new Test1(); test1.method1(); } }
以上代码正常,public修饰的内容访问不受限制。
还是上面的代码,将Test1类的修饰符改为private或者protected,提示如下:
然后就以为类(非内部类)的修饰符只能是public、abstract、final,访问权限方面只能是public修饰。在看内部类的时候看到说“外部类只能被public和包访问两种权限修饰”,特地测试了下。
去掉Test1类的修饰符,Test2调用报错,无法找到对应的类。
将Test2与Test1放在同一个包下,不报错。
可见类(非内部类)可用public和default两种权限修饰符修饰,且默认为default;