2

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

 public void explain() {

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

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

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

4

2 回答 2

2

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

public void explain(Instances i)

并在您的子类中调用它。您不需要覆盖任何东西,并从基类中获得代码重用的好处。或者,如果有一些更复杂的逻辑,您可以尝试模板方法模式,例如

基类

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);
    }
}
于 2013-10-23T17:57:50.223 回答
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
}
于 2013-10-23T18:01:06.440 回答