温馨提示×

温馨提示×

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

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

Java Subclass 子类重写父类方法

发布时间:2025-10-19 01:36:11 来源:亿速云 阅读:92 作者:小樊 栏目:编程语言

在Java中,子类可以通过重写(Override)父类的方法来实现多态。重写意味着子类提供了一个与父类中具有相同名称、参数类型和返回类型的新实现。以下是如何在Java中重写父类方法的步骤:

  1. 创建一个父类(如果还没有的话):
public class Parent {
    public void display() {
        System.out.println("This is the Parent class method.");
    }
}
  1. 创建一个子类,并继承父类:
public class Child extends Parent {
    // ...
}
  1. 在子类中重写父类的方法:
public class Child extends Parent {
    @Override
    public void display() {
        System.out.println("This is the Child class method.");
    }
}

这里,我们使用了@Override注解,它是一个可选的注解,用于指示我们打算重写父类的方法。这有助于编译器检查我们是否正确地重写了方法,以及是否满足了重写的要求(例如,方法签名必须与父类中的方法相同)。

  1. 在主类或其他地方测试重写的方法:
public class Main {
    public static void main(String[] args) {
        Parent parent = new Parent();
        parent.display(); // 输出:This is the Parent class method.

        Child child = new Child();
        child.display(); // 输出:This is the Child class method.

        // 使用父类引用指向子类对象
        Parent parentWithChild = new Child();
        parentWithChild.display(); // 输出:This is the Child class method.
    }
}

在这个例子中,我们可以看到,当我们使用子类对象调用display()方法时,将执行子类中重写的方法。此外,当我们使用父类引用指向子类对象时,仍然会执行子类中重写的方法。这是因为Java中的方法调用是基于对象的实际类型,而不是引用类型。

向AI问一下细节

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

AI