覆盖超类中的方法

时间:2013-10-23 17:55:46

标签: java inheritance subclass superclass method-overriding

我的超类中有一个方法设置......

 public void explain() {

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

我需要在子类中覆盖这个相同的方法来打印出原始输出消息,但是这个方法的新实例需要打印出在子类中设置的不同值

我对最重要的一点感到困惑(因为我对此知之甚少),并希望得到解释。

2 个答案:

答案 0 :(得分:2)

所以只需在基类参数中给出方法,如

public void explain(Instances i)

并在您的子类中调用它。您不需要覆盖任何内容,并且可以从基类中重用代码。或者,如果有一些更复杂的逻辑,你可以尝试Template method pattern喜欢

基础课程

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);
    }
}

答案 1 :(得分:0)

在您的子类中:

@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
}