我从抽象类 X 继承了一个公共方法,但我不想覆盖该方法来复制和粘贴整个内容并添加另外两行代码,我只想使用已经在抽象类中,无需重新编写,只需编写额外的两行.我已经编写 Java 一个多月了,但到目前为止我还没有找到解决方法,这可能吗?
I inherited a public method from an abstract class X but instead of overriding the method to copy and paste the whole content plus add two more lines of code, I would like to just use the code that is already in the abstract class without writing it all over again and just write the extra two lines. I've been coding Java for a little over a month and I haven't found a way around this so far, is it even possible?
这是抽象类中的方法:
public UsineOrganisme copieAUsine() { UsineOrganisme usine = new UsineOrganisme(); usine.setNomEspece(this.nomEspece); usine.setEnergieEnfant(this.energieEnfant); usine.setBesoinEnergie(this.besoinEnergie); usine.setEfficaciteEnergie(this.efficaciteEnergie); usine.setResilience(this.resilience); usine.setFertilite(this.fertilite); usine.setAgeFertilite(this.ageFertilite); usine.setDebrouillardise(this.debrouillardise); //Ajouter les aliments de l'espèce for (String especeComestible : this.getAliments()) { usine.addAliment(especeComestible); } return usine; }并且我希望我在普通类中继承的方法相同,但在返回usine"之前添加这两行.
And I want my inherited method in the normal class to be the same but add these two lines before returning "usine".
public UsineOrganisme copieAUsine() { //Same Code but adding these two setters usine.setVoraciteMin(this.voraciteMin); usine.setVoraciteMax(this.voraciteMax); return usine; } 推荐答案是的,在你的情况下,你只需要调用超级实现:
Yes, in your case you just have to call the super implementation:
@Override public UsineOrganisme copieAUsine(){ UsineOrganisme usine = super.copieAUsine(); usine.setVoraciteMin(this.voraciteMin); usine.setVoraciteMax(this.voraciteMax); return usine; }更多推荐
我可以在不覆盖整个方法的情况下向继承的方法添加代码吗?
发布评论