Java修饰符public,protected,default,private访问权限
2024-09-01 18:23:50
public
具有最大的访问权限。所有类可访问。
protected
主要是用来保护子类。自身、子类及同一个包中类可以访问
default
没有加修饰符的。有时候也称为friendly,它是针对本包访问而设计的。同一包中可以访问。
private
访问权限仅限于类的内部,是一种封装的体现。只能被自己访问
类内部 | 子类内部(本包) | 其他类(本包) | 子类内部(外部包) | 其他类(外部包) | |
public | O | O | O | O | O |
protected | O | O | O | O | X |
default | O | O | O | X | X |
private | O | X | X | X | X |
示例代码
包apkg
ParentA.java
package apkg; public class ParentA {
public String publicVariable = "public";
protected String protectedVariable = "protected";
String variable = "default";
private String privateVariable = "privater"; public void show() {
System.out.println(this.publicVariable);
System.out.println(this.protectedVariable);
System.out.println(this.variable);
System.out.println(this.privateVariable);
} public static void main(String[] args) {
ParentA apkg = new ParentA();
apkg.show();
}
}
SonA.java
package apkg; public class SonA extends ParentA {
public void show() {
System.out.println(this.publicVariable);
System.out.println(this.protectedVariable);
System.out.println(this.variable);
//System.out.println(this.privateVariable);// 无法访问
}
}
UncleA.java
package apkg; import apkg.ParentA; public class UncleA {
public void show() {
ParentA apkg = new ParentA();
System.out.println(apkg.publicVariable);
System.out.println(apkg.protectedVariable);
System.out.println(apkg.variable);
//System.out.println(apkg.privateVariable);// 无法访问
}
}
包bpkg
SonB.java
package bpkg; import apkg.ParentA; public class SonB extends ParentA {
public void show() {
System.out.println(this.publicVariable);
System.out.println(this.protectedVariable);
//System.out.println(this.variable);// 无法访问
//System.out.println(this.privateVariable);// 无法访问
}
}
UncleB.java
package bpkg; import apkg.ParentA; public class UncleB {
public void show() {
ParentA apkg = new ParentA();
System.out.println(apkg.publicVariable);
//System.out.println(apkg.protectedVariable);// 无法访问
//System.out.println(apkg.variable);// 无法访问
//System.out.println(apkg.privateVariable);// 无法访问
}
}
最新文章
- MongoDB 聚合操作
- Servlet 总结
- [itint5]支持删除的后继查询
- Mysql 5.5 replication 多数据库主从备份Master-Slave配置总结
- PHP伪静态与短链接
- iOS网络之数据请求GET和POST
- hdu4496 D-City
- coolite 获取新的页面链接到当前页面指定位置Panel的运用
- Linux进程管理的学习
- xcfe桌面快捷键整理
- 其它 nginx
- C语言中的模运算-hdu6124(打表,找规律)
- Android UI系列-----LinearLayout的综合使用
- mui做的苹果app生成ipa后放到自己的网站上让人下载安装
- 【转】每天一个linux命令(5):rm 命令
- [JQuery插件系列]-强烈推荐10个非常不错的jQuery工具提示插件
- 【SQL Server高可用性】数据库复制:SQL Server 2008R2中数据库复制
- HTTP和HTTPS的请求和响应
- Tomcat 配置虚拟路径保存、访问图片
- Python 进程线程协程 GIL 闭包 与高阶函数(五)