我可以在不覆盖整个方法的情况下向继承的方法添加代码吗?

编程入门 行业动态 更新时间:2024-10-28 16:27:49
本文介绍了我可以在不覆盖整个方法的情况下向继承的方法添加代码吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我从抽象类 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; }

更多推荐

我可以在不覆盖整个方法的情况下向继承的方法添加代码吗?

本文发布于:2023-11-23 09:19:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1620920.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   情况下   代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!