Overriding a method that's in the superclass

僤鯓⒐⒋嵵緔 提交于 2019-12-24 02:58:15

问题


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.


回答1:


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

Base class

public abstract class Base {

    public abstract explain(Instances i);

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

Subclass

public class Subclass extends Base {

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



回答2:


In your subclass:

@override //Throw a warning if you're not overidding anything
public void explain(){
    super.explain();//This will call the method from the superclass.

     //Do what you have to do in the sub-class
}


来源:https://stackoverflow.com/questions/19548983/overriding-a-method-thats-in-the-superclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!