覆盖超类中的方法 [英] Overriding a method that's in the superclass

查看:189
本文介绍了覆盖超类中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在超类中设置了一个方法...

I have a method set in my superclass...

 public void explain() {

     for (Item item: Instances) {
         System.out.println(item.getname + " is in location " + item.place):
     }
 }

我需要在子类中重写相同的方法以打印出原始输出消息,但是此方法的新实例需要打印出子类中已设置的不同值

I need to override this same method in the subclass to print out the original output message but the new instance for this method needs to print out different values that have been set in the subclass

我对最重要的部分(我对此一无所知)感到困惑,并想作一个解释.

I'm confused with the overriding bit (as I know little about it) and would like an explanation.

推荐答案

因此,只需在基类参数中给出方法即可,例如

So just give the method in base class parameter like

public void explain(Instances i)

并在您的子类中调用它.您无需重写任何内容,就可以从基类中受益于代码重用.或者,如果逻辑更复杂,您可以尝试模板方法模式,例如

and call it in your subclass. You don't need to override anything and have the benefit of code reuse from the base class. Or, in case some more complicated logic you can try Template method pattern like

基类

public abstract class Base {

    public abstract explain(Instances i);

    public void print(Item i) {
        //do something
    }
}

子类

public class Subclass extends Base {

    @Override 
    public void explain(Instance instances) {
         //do some logic and call print in loop
         print(someItemfromInstances);
    }
}

这篇关于覆盖超类中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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