Java 中的受保护访问修饰符
超类中声明为 protected 的变量、方法和构造函数只能由其他包中的子类或受保护成员类所属包内的任何类访问。
受保护的访问修饰符不能应用于类和接口。方法、字段可以声明为受保护的,但接口中的方法和字段不能声明为受保护的。
受保护的访问权限让子类有机会使用辅助方法或变量,同时防止无关的类尝试使用它。
示例
The following parent class uses protected access control, to allow its child class override openSpeaker() method -
class AudioPlayer {
protected boolean openSpeaker(Speaker sp) {
// implementation details
}
}
class StreamingAudioPlayer {
boolean openSpeaker(Speaker sp) {
// implementation details
}
}在此,如果我们将 openSpeaker() 方法定义为私有的,则除了 AudioPlayer 之外,其他任何类都无法访问它。如果我们将它定义为公有的,那么它将对所有外界开放。但是我们的目的是仅将其方法公开给其子类,这就是我们使用受保护修饰符的原因。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP