#What does this code output and why does it do that?

23 messages · Page 1 of 1 (latest)

high radish
#

Here is the question:

** Consider the following class definition:**

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

What is printed when the following code is executed?

Student s = new GradStudent();
System.out.println(s.getInfo());

(A) Pizza
(B) Taco
(C) Studying
(D) Eating
(E) Studying
Eating

When I followed the code, I saw that super.getInfo() returns "Studying" and then the next line (return "Eating") will return Eating. I'm confused why the answer is only eating. Doesn't "studying" also get returned? And shouldn't it be the first thing returned? This is very confusing and I'm sorry if its a dumb question

coral treeBOT
#

This post has been reserved for your question.

Hey @high radish! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

proper echo
#

super.getInfo() is called in a void

#

nothing is done with its return value

tender pecan
#

Are you calling another method from another class?

proper echo
#

you only return "Eating", because the return statement only says to return "Eating"

high radish
high radish
proper echo
tender pecan
#

it should print eating then

high radish
proper echo
#

no

high radish
#

sorry I meant studying*

proper echo
#

ok then yes
"Studying" is retrieved from the Student.getInfo() method, and nothing is done with it
then the GradStudent.getInfo() method returns only "Eating", because that is what it is hard-coded to do

#

simply retrieving a value from another method does not add that value to this method's return value

#

methods only return that which is actually in the return statement

high radish
#

Ohh, that makes more sense.

So in this situation the only way to get "studying" was if we did something like:

return super.getInfo();
proper echo
#

yes

tender pecan
#

yes like that

high radish
#

wow that makes more sense

#

thank you so much

coral treeBOT
# high radish thank you so much

If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.