Can I add code to an inherited method without overriding the whole method? (Java)

so 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?

This is the method inside the abstract class :

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

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

Thank you for your time!!

Answer

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

Leave a Reply

Your email address will not be published. Required fields are marked *