// 定义一个父类
class Parent {
// protected修饰的成员变量,子类可以访问,同一包内其他类也可以访问
protected String name = "Parent";
// protected修饰的方法,子类可以访问,同一包内其他类也可以访问
protected void display() {
System.out.println("This is the parent class.");
}
}
// 定义一个子类继承自Parent
class Child extends Parent {
// 子类可以访问父类中的protected成员变量和方法
public void show() {
System.out.println("Name: " + name);
display();
}
}
// 定义一个不同包内的类来演示protected的访问限制
class OtherClass {
// 不能直接访问Parent类中的protected成员变量和方法,除非通过继承
// 因为OtherClass不是Parent的子类,且不在同一个包内
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.show(); // 输出: Name: Parent 和 This is the parent class.
}
}
protected修饰符的作用:protected修饰的成员(变量或方法)可以在同一包内被任何类访问,也可以被不同包内的子类访问。但是,不同包内的非子类无法直接访问这些成员。Parent类中定义了一个protected修饰的字符串变量name和一个protected修饰的方法display()。Child类继承了Parent类,并且可以在show()方法中访问父类的protected成员。OtherClass类位于不同的包中,且没有继承Parent类,因此它无法直接访问Parent类中的protected成员。上一篇:java修改文件名
下一篇:java 随机
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站