0

Here is the code:

class Food {
    Food() { printFlavor(); }
    void printFlavor() { System.out.println("bland"); }
}
class Pepper extends Food {
    void printFlavor() { System.out.println("spicy"); }
}
public class Lunch {
    public static void main(String[] args) {
        Food lunch = new Pepper();
    }
}

When I ensure to run its own method of its own class with this keyword, it still runs base method.

class Food {
    Food() { this.printFlavor(); }
    void printFlavor() { System.out.println("bland"); }
}
class Pepper extends Food {
    void printFlavor() { System.out.println("spicy"); }
}
public class Lunch {
    public static void main(String[] args) {
        Food lunch = new Pepper();
    }
}

My question is not how to resolve this issue. My question is why parent constructor chooses to call base method instead of parent method?

1

1 Answer 1

0

The reason is whenever you create an object of child class ,the constructor of parent class gets called first(by default) followed by the child class constructor.

To run the parent class method , you need to create parent class object Food obj = new Food. The object type that you are creating is not of Food Class , it is of Pepper Class.

Sign up to request clarification or add additional context in comments.

2 Comments

So, for method, base methods are called first and then parent methods????
No just for constructor , the base class constructor is called first then the child class cons is called

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.