当前位置:首页 > Java

java子类如何调用父类的方法

2026-03-03 11:45:59Java

子类调用父类方法的方式

在Java中,子类可以通过super关键字或直接调用(当未被重写时)来访问父类的方法。以下是具体实现方式:

使用super关键字

当子类重写了父类方法,但仍需调用父类原始方法时,使用super.methodName()

java子类如何调用父类的方法

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

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

直接调用未重写的方法

若子类未重写父类方法,可直接通过子类实例调用:

java子类如何调用父类的方法

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

class Child extends Parent {
    void callParent() {
        print(); // 直接调用继承的父类方法
    }
}

调用父类构造方法

子类构造方法中可通过super()调用父类构造方法(必须位于子类构造方法首行):

class Parent {
    Parent(String msg) {
        System.out.println(msg);
    }
}

class Child extends Parent {
    Child() {
        super("Calling parent constructor"); // 调用父类构造方法
    }
}

多级继承中的调用

在多层继承中,super会逐级向上查找最近父类的方法:

class Grandparent {
    void show() {
        System.out.println("Grandparent");
    }
}

class Parent extends Grandparent {
    @Override
    void show() {
        super.show(); // 调用Grandparent的方法
    }
}

class Child extends Parent {
    @Override
    void show() {
        super.show(); // 调用Parent的方法
    }
}

标签: 子类方法
分享给朋友:

相关文章

vue commit 方法实现

vue commit 方法实现

Vue 中 Commit 方法的实现 在 Vue 中,commit 方法是 Vuex 的核心功能之一,用于提交 mutation 来修改状态。以下是实现 commit 方法的关键步骤: 初始化 St…

vue实现方法同步

vue实现方法同步

Vue 中实现方法同步的方式 在 Vue 中,方法通常是异步执行的,但可以通过以下方式实现同步效果或控制执行顺序: 使用 async/await 通过将方法标记为 async 并使用 await 关…

vue watch 实现方法

vue watch 实现方法

监听基本数据类型 在Vue中使用watch监听基本数据类型(如String、Number、Boolean)时,可以直接在watch选项中定义: data() { return { mes…

前端功能实现方法vue

前端功能实现方法vue

前端功能实现方法(Vue) 使用Vue CLI创建项目 通过Vue CLI快速初始化项目,安装依赖并启动开发服务器。 npm install -g @vue/cli vue create my-…

react父组件如何调用子组件的方法

react父组件如何调用子组件的方法

使用 ref 直接调用子组件方法 在父组件中通过 useRef 或 createRef 创建 ref,并将其传递给子组件。子组件需要使用 forwardRef 和 useImperativeHandl…

php实现接口方法

php实现接口方法

PHP 实现接口方法 在 PHP 中,接口(Interface)用于定义一组方法的规范,类通过实现接口来遵循这些规范。以下是实现接口方法的具体步骤和示例: 定义接口 接口通过 interface 关…