Java 中 protected 和 default 访问修饰符有什么区别?
**Protected** 访问修饰符在**同一包内可见**,并且在**子类中也可见**,而**Default** 是一个**包级访问修饰符**,它可以在**同一包内可见**。
Protected 访问修饰符
- **Protected** 在同一包内起作用类似于 public,而在包外起作用类似于 private。
- **Protected** 仅对子类对象在包外也起作用类似于 public。
- **Protected** 字段或方法不能用于类和接口。
- 在超类中声明为 **protected** 的字段、方法和构造函数只能被其他包中的子类访问。
- 同一包中的类也可以访问 **protected** 字段、方法和构造函数,即使它们不是 **protected** 成员所属类的子类。
示例
public class ProtectedTest {
// variables that are protected
protected int age = 30;
protected String name = "Adithya";
/**
* This method is declared as protected.
*/
protected String getInfo() {
return name +" is "+ age +" years old.";
}
public static void main(String[] args) {
System.out.println(new ProtectedTest().getInfo());
}
}输出
Adithya is 30 years old.
Default 访问修饰符
- 如果类成员**没有任何访问修饰符**,则认为它是 **Default**。
- **Default** 在同一包内起作用类似于 public,而在包外起作用类似于 private。
- 任何类的 **Default** 成员都可以被同一包内的任何内容访问,但在任何情况下都不能在包外访问。
- **Default** 将访问权限限制在**包级别**,即使扩展了具有默认数据成员的类,我们也无法访问。
示例
public class DefaultTest {
// variables that have no access modifier
int age = 25;
String name = "Jai";
/**
* This method is declared with default aacees specifier
*/
String getInfo() {
return name +" is "+ age +" years old.";
}
public static void main(String[] args) {
System.out.println(new DefaultTest().getInfo());
}
}输出
Jai is 25 years old.
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP