温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java Protected方法如何调用

发布时间:2025-07-01 11:18:03 来源:亿速云 阅读:111 作者:小樊 栏目:编程语言

在Java中,protected方法是一种特殊的方法访问修饰符,它允许子类访问父类的方法。要调用protected方法,您需要遵循以下步骤:

  1. 创建一个子类,继承父类。
  2. 在子类中,使用super关键字调用父类的protected方法。

下面是一个简单的例子来说明如何调用protected方法:

// 父类
public class Parent {
    protected void printMessage() {
        System.out.println("This is a protected method in the parent class.");
    }
}

// 子类
public class Child extends Parent {
    public void callProtectedMethod() {
        // 使用super关键字调用父类的protected方法
        super.printMessage();
    }
}

// 测试类
public class Test {
    public static void main(String[] args) {
        Child child = new Child();
        child.callProtectedMethod(); // 输出:This is a protected method in the parent class.
    }
}

在这个例子中,我们创建了一个名为Parent的父类,其中包含一个名为printMessage的protected方法。然后,我们创建了一个名为Child的子类,该子类继承了Parent类。在Child类中,我们创建了一个名为callProtectedMethod的方法,该方法使用super关键字调用父类的printMessage方法。最后,在Test类中,我们创建了一个Child对象,并调用了callProtectedMethod方法,从而间接调用了父类的protected方法。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI