protected权限

来源:互联网 发布:淘宝详情页排版技巧 编辑:程序博客网 时间:2024/05/16 23:44

1、我们知道private权限修饰的成员,仅限自己访问


2、我们知道friendly(default)权限修饰的成员,仅限包内访问


3、那么protected权限呢?下面就为您解密

package com.wangyuanwai.testprotect;public class ProtectDemo {protected void printClassName() {System.out.println(ProtectDemo.class.getName());}}


package com.wangyuanwai.testprotect;public class Drive1 {public static void main(String args[]) {ProtectDemo demo = new ProtectDemo();demo.printClassName();}}

Drive1与ProtectDemo在同一个包下com.wangyuanwai.testprotect ,可以访问protected的方法 printClassName


新建了一个包,试着访问protected方法printClassName,没有访问权限

package com.wangyuanwai.testprotect.two;import com.wangyuanwai.testprotect.ProtectDemo;public class Drive2 {public static void main(String args[]) {ProtectDemo demo = new ProtectDemo();demo. //不能访问printClassName()方法}}


通过extends,扩展后,可以访问protected修饰的方法

package com.wangyuanwai.testprotect.two;import com.wangyuanwai.testprotect.ProtectDemo;public class ProtectDemoUp extends ProtectDemo {public static void main(String args[]) {new ProtectDemoUp().printClassName();}}

4、总结

答:protected修饰的成员,通过组合的方式,在包外的是不允许的访问的,但是通过继承(extends) 的在包外就可以被访问




0 0
原创粉丝点击