如何重写Java中的方法,然后调用超类方法 [英] how to override a method in java and then call the superclass method

查看:469
本文介绍了如何重写Java中的方法,然后调用超类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的java子类中重写超类中的方法,然后从超类中调用重写的方法.这是正确的方法吗?我要重写的超类中的方法称为describe()

I am trying to override a method in the superclass in my java subclass and then call the overriden method from the superclass. Is this the correct way to do it. The method in the super class i want to overrride is called describe()

 public static void describe()
    {
        Item.describe();



    }

推荐答案

使用super关键字.

@Override
public void describe() {
    super.describe();
}

请注意,虽然不是必需的,但注释是正确的".

Note the annotation which although is not necessary is "correct".

如前所述,静态方法不会被继承.可以使用反射的静态方法来模仿多态行为,但是我不建议初学者使用.这只是您可以做的事情.您可以在子类中创建相同的静态方法签名,并在超类引用上使用Method.invoke(),并且在功能上与覆盖静态方法相同.

As was pointed out, static methods do not get inherited. It's possible to imitate polymorphic behavior with static methods using reflection but I do not recommend this for a beginner. It's just something that you can do. You can create identical static method signatures in the subclasses and use Method.invoke() on a superclass reference and functionally it is the same as overriding a static method.

这篇关于如何重写Java中的方法,然后调用超类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆