// 示例代码:展示 Java 中 protected 访问修饰符的使用
// 定义一个父类
class Parent {
// 使用 protected 修饰符定义一个成员变量
protected String name = "Parent";
// 使用 protected 修饰符定义一个方法
protected void display() {
System.out.println("This is a protected method in Parent class.");
}
}
// 定义一个子类,继承自 Parent 类
class Child extends Parent {
// 子类可以直接访问父类中的 protected 成员
void show() {
System.out.println("Name from Parent: " + name);
display(); // 调用父类的 protected 方法
}
}
// 定义一个不同包中的类
package anotherPackage;
import javaProtectedExample.Parent;
class AnotherClass {
// 只有在继承的情况下才能访问 protected 成员
public void accessProtected() {
Parent p = new Parent();
// 编译错误:不能直接访问另一个包中非子类的 protected 成员
// System.out.println(p.name);
}
}
protected 访问修饰符:它允许同一个包内的类、子类(即使在不同的包中)访问该成员。但是,不同包中的非子类无法直接访问 protected 成员。Parent 类中的 name 和 display() 方法是 protected 的,因此它们可以在同一包中的类或不同包中的子类中被访问。Child 类继承了 Parent 类,并能够访问 protected 的成员和方法。AnotherClass 属于不同的包,且不是 Parent 的子类,因此无法直接访问 Parent 类中的 protected 成员。下一篇:java回调函数的使用场景
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站