温馨提示×

温馨提示×

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

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

Java中重写方法时如何调用父类方法

发布时间:2025-10-11 23:11:20 来源:亿速云 阅读:107 作者:小樊 栏目:编程语言

在Java中,要在子类中重写方法的同时调用父类的方法,可以使用super关键字。super关键字表示父类对象,通过它可以访问父类的属性和方法。

以下是一个简单的例子:

class Parent {
    void display() {
        System.out.println("Parent class method");
    }
}

class Child extends Parent {
    // 重写父类的display方法
    void display() {
        super.display(); // 调用父类的display方法
        System.out.println("Child class method");
    }
}

public class Main {
    public static void main(String[] args) {
        Child child = new Child();
        child.display(); // 输出:Parent class method
                         //       Child class method
    }
}

在这个例子中,Child类继承了Parent类,并重写了display()方法。在Child类的display()方法中,我们使用super.display()调用了父类Parentdisplay()方法。当我们创建一个Child对象并调用其display()方法时,它会先输出"Parent class method",然后输出"Child class method"。

向AI问一下细节

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

AI