Search code examples
javainheritanceencapsulationoverriding

@Override Java Parent Class


This is my code in parent class

public boolean ChoiceOfItem(){
    if (bread)
        this.Choice("bread");
    if (meat)
        this.Choice("meat");
    if (lettuce)
        this.Choice("lettuce");
    if (tomato)
        this.Choice("tomato");
    if (carrot)
        this.Choice("carrot");
    return false;
}

and this one is from extended(Not parent) class:

@Override
public boolean ChoiceOfItem() {
    if (ryeBread)
        this.Choice("ryeBread");
    return false;
}

My question is what is wrong and what is right here? Looking forward to your messages. I'll be able to send the whole code if it is necessary.


Solution

  • ChoiceOfItem probably needs to return true when handled some item, hence return false only in that case.

    public boolean choiceOfItem(){
        if (bread)
            this.Choice("bread");
        else if (meat)
            this.Choice("meat");
        else if (lettuce)
            this.Choice("lettuce");
        else if (tomato)
            this.Choice("tomato");
        else if (carrot)
            this.Choice("carrot");
        else return false;
        return true;
    }
    
    @Override
    public boolean choiceOfItem() {
        if (super.choiceOfItem())
            return true;
        if (ryeBread) {
            this.Choice("ryeBread");
            return true;
        }
        return false;
    }