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

发布时间:2025-04-09 14:30:36 作者:小樊
来源:亿速云 阅读:113

在Java中,如果你想在子类中重写一个方法,但仍然想调用父类的实现,你可以使用super关键字。super关键字表示父类对象,可以用来调用父类的方法。以下是一个简单的例子:

class Parent {
    void print() {
        System.out.println("This is the Parent class method.");
    }
}

class Child extends Parent {
    void print() {
        System.out.println("This is the Child class method.");
    }

    void callParentMethod() {
        super.print(); // 调用父类的print方法
    }
}

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

在这个例子中,Child类重写了Parent类的print()方法。但是,我们在Child类中添加了一个新的方法callParentMethod(),在这个方法中,我们使用super.print()调用了父类的print()方法。所以当我们调用child.callParentMethod()时,它会输出父类的方法实现。

推荐阅读:
  1. java重写与重载的区别
  2. Java编程关于子类重写父类方法问题的理解

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

java

上一篇:Java continue语句可以用于switch吗

下一篇:Java Override重写的基本原则

相关阅读

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

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