Beta 44
4 44
Beta 44
44 44
João Victor Gomes wrote:Hello Shane.
The expression needs to be evaluated first.
b.h evaluates to 4, because b is of type Baap, and it defines the value 4 for the instance variable h. Then, the b.getH() expression will be evaluated, but since it is a method that returns a value, the method is executed first, and inside the getH() method, there is a System.out.println() printing the value of h, and then it will return this h value to complete the evaluation of the expression 1. So, first the method getH() is executed, and it will return a value. Then, after the evaluation of expression 1 is completed, it will print the resulting values.
Pay attention to the dynamic binding here. The variable b is of type Baap, but its object is of type Beta, so at runtime the getH() from Beta class will be used, and it will print Beta and 44 (the value of h inside Beta).
Shane Jensen wrote:How does this explain that Beta is printed before everything else? Even before b.h?
João Victor Gomes wrote:
Shane Jensen wrote:How does this explain that Beta is printed before everything else? Even before b.h?
As I said, the expression needs to be fully evaluated, so before the following code prints anything, it must evaluate b.h and b.getH()
First, it evaluates b.h to 4, but before printing 4 44, it must define the value of b.getH(). And how it is done? By calling the method getH() that returns the value to be used in the expression. But if you are calling a method, the method must be executed completely before it returns the value, and since this method is printing - System.out.println("Beta " + h); - before returning the value to be used in the first expression, that's why you get Beta 44 before 4 44.
At line 1, when b.getH() starts to be evaluated, this line stops for a moment, and the method getH() is executed, printing Beta 44 and returning the value of h, finishing its execution, and then the control returns to the expression represented in line 1, so it can complete its execution.
Shane Jensen wrote:
Right. So if I understand correctly: all parameters within a single System.out.println() statement need to be evaluated before anything can be printed? That's new to me, but it does make sense. Thank you for your detailed explanation!
Shane Jensen wrote:The following question comes from one of Enthuware's mock exams. If I'm not allowed to post this: my apologies, and I'll remove the post.
Shane Jensen wrote:I don't understand how this is possible. As far as I can tell, the very first variable that should be printed by this code is b.h, which is 4. How can Beta be printed first?
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime. |