// 示例代码:protected在Java中的用法
// 定义一个父类
class Parent {
// 使用protected修饰的成员变量
protected String name = "Parent";
// 使用protected修饰的方法
protected void display() {
System.out.println("这是父类中的方法,name: " + name);
}
}
// 定义一个子类,继承自Parent
class Child extends Parent {
// 子类可以直接访问父类中的protected成员和方法
void show() {
System.out.println("这是子类中的方法,访问父类的name: " + name);
display();
}
}
// 定义一个不同包下的类
class AnotherClass {
// 不能直接访问Parent类中的protected成员和方法
// 因为AnotherClass不在同一个包中,也不是Parent的子类
}
// 测试类
public class TestProtected {
public static void main(String[] args) {
Parent parent = new Parent();
Child child = new Child();
// 父类对象可以调用protected方法
parent.display(); // 这里实际上不允许,因为protected成员不能被其他包中的非子类访问
// 子类对象可以调用protected方法
child.show();
}
}
protected
修饰符:protected
修饰符允许同一包中的类以及所有子类(无论是否在同一包中)访问该成员或方法。Parent
:定义了一个protected
的成员变量name
和一个protected
的方法display()
。这些成员可以在同一包内的类中访问,也可以在子类中访问。Child
:继承了Parent
类,并且可以直接访问Parent
类中的protected
成员和方法。TestProtected
:创建了Parent
和Child
的对象,并展示了如何调用protected
方法。注意,parent.display()
在不同包中是不允许的,除非通过子类来访问。上一篇:java aes解密
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站