Java 中的受保护的访问修饰符
在超类中声明为受保护的变量、方法和构造函数只能由其他包中的子类或受保护成员类包中的任何类访问。
受保护的访问修饰符不能应用于类和接口。可以将方法、字段声明为受保护,但接口中的方法和字段不能声明为受保护。
受保护的访问允许子类使用辅助方法或变量,同时防止不相关的类尝试使用它。
示例
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