I am taking a practice test for Java certification and got this question:
What will the following code print?
This is the answer:
I understand the part about overriding and h being shadowed or not. What I'm confused about is what exactly happens when getH() is passed as a parameter. When it is passed as a parameter, does it get to output its println()? Apparently it does. So then why is "Beta 44" first? Why does getH() get executed before b.h is printed?
Patrick Kasarski wrote: So then why is "Beta 44" first? Why does getH() get executed before b.h is printed?
Because Java needs to know the values to pass to System.out.println(). The value of b.h is already known since it is just a variable. Since getH() is a method, it needs to be executed. Then both (b.h and the result of getH()) get passed to println at the same time. It isn't until that point that it executes.