在Java中,子类可以通过以下方式调用父类的protected方法:
1. 在子类中直接调用父类的protected方法。
2. 如果子类和父类在同一个包中,子类可以通过父类的引用来调用父类的protected方法。
以下是一个示例:
```java
// 父类
public class Parent {
protected void protectedMethod() {
System.out.println("This is a protected method in the parent class.");
}
}
// 子类
public class Child extends Parent {
public void callProtectedMethod() {
// 直接调用父类的protected方法
protectedMethod();
}
}
// 测试类
public class Test {
public static void main(String[] args) {
Child child = new Child();
child.callProtectedMethod(); // 输出:This is a protected method in the parent class.
}
}
```
在这个例子中,`Child`类继承了`Parent`类,并且重写了`callProtectedMethod`方法。在`callProtectedMethod`方法中,我们可以直接调用父类的`protectedMethod`方法。
腾讯云相关产品推荐:腾讯云提供了云服务器、云数据库、云存储等多种云计算产品,可以帮助您快速搭建和部署应用。您可以访问腾讯云官网(https://cloud.tencent.com/)了解更多信息。... 展开详请