Hello. Sorry if there's a topic already for this but I have a doubt regarding question 20 of chapter 1 of the OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide.
The solution says that C. is the correct answer. I did test it out and it does output "walk, toddle," but this doesn't make sense to me. Since we're refering to the instance variables it should be "walk, walk,". It's true that BabyRhino is a static class but I'm not using the class itself but the instance of the class. And since it extends FourLegged and FourLegged's walk variable value is "walk,".
Can someone explain me why exactly the output is "toddle," for the second part? I understand it has something to do with the static context.
Welcome to CodeRanch! I've added the book publisher to your subject. (There are a few books with similar names)
This is definitely one of the trickiest things in the chapter! The fact that it is a static class isn't relevant to the behavior. We made a static class so we could call it directly from the main method. Let's build up the example slowly to understand. (I removed the commas in the strings and renamed the variables to make this post easier to read)
First, you should be able to see why this code prints "walk"
This time with BabyRhino. Again, you should be able to see why this prints "toddle" since there is only walk variable.
Combining the two, this prints walk and toddle. Still should be straightforward. All I did was combine the previous examples and have one class extend the other. No behavior has changed.
Finally comes the trick. I changed the first line in the main method. Now we have a BabyRhino object in a FourLegged reference. The trick is that you have to notice walk is a variable and not a method. For a variable, you get the one for the reference and not the implementing class. So it still prints walk and toddle even though there are two BabyRhino objects.