nick woodward wrote:Anyway I believe it's because the println in main has to evaluate the 'getH()' method before it can print anything, it's printing the concatenation, not each individual element. So "beta + h" in class Question37's method getH() preceeds main's System.out.println(b.h +""+ b.getH()).
You are absolutely spot-on!
When this line of code is executed
this is the flow of execution:
1/
b.h is evaluated ->
4 (rule 1: which instance variable is accessed, is determined at compile time based on the type of the reference variable ->
b is of type
Baap)
2/
4 and
" " are concatenated ->
"4 "
3/
b.getH() is evaluated ->
getH() method in
Question37 class is executed (rule 2: which method is executed, is determined at runtime based on the type of the actual object -> actual object is of type
Question37)
3a/ the statement
System.out.println("beta "+h); is executed
3a1/
h is evaluated ->
44
3a2/
"beta " and
44 are concatenated ->
"beta 44"
3a3/
"beta 44" is
printed
3b/
h is evaluated ->
44
3c/
44 is returned
4/
"4 " and
44 are concatenated ->
"4 44"
5/
"4 44" is
printed
And that's why
"beta 44" is in the output before
"4 44".
This (very) detailed explanation lists 2 very simple (and hopefully easy to remember) but
very, very, very important rules:
Which instance variables you can access is determined at compile time based on the reference variable type.Which instance methods you can call/invoke is determined at compile time based on the reference variable type. Which instance method is actually executed is decided at runtime based on the type of the actual object (= polymorphism).
Hope it helps!
Kind regards,
Roel