Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why doesn't super. call the superclass method in this code?

When I execute this code, it only returns "Eating" instead of "Studying" AND "Eating." Can anyone explain it?

public class Student {
    public String getFood() {
        return "Pizza";
    }
    public String getInfo(){
        return "Studying";
    }
}

public class GradStudent extends Student {
    public String getFood(){
        return "Taco";
    }
    public String getInfo(){
        super.getInfo();
        return "Eating";
    }

    public static void main(String[] args){
        Student s = new GradStudent();
        System.out.println(s.getInfo());
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In the getInfo() method of the Student is getting invoked, but currently you are not using the result.

If, in the GradStudent class, you want to return a String that combines the result of the Student.getInfo method with the specific value from GradStudent you could do something like this:

public class GradStudent extends Student {
    public String getFood(){
        return "Taco";
    }
    public String getInfo(){
        String studentInfo = super.getInfo();
        return studentInfo + " Eating";
    }

    public static void main(String[] args){
        Student s = new GradStudent();
        System.out.println(s.getInfo());
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading