Page 1 of 1

Mock exam question

Posted: Sat Apr 10, 2021 7:34 am
by dantan267@gmail.com
Hi there,

I am trying to understand the code from Question 63, Test 1 of your IZ0-808 mock exam.

A few lines from the code:

public static void main(String[] args) {

Baap b = new Beta();
System.out.println(b.h+ " " + b.getH()); //(A), I am stuck at this line, see question below
//Beta bb = (Beta) b; //i commentend these out
//System.out.println(bb.h + " " + bb.getH());

}

The output in IntelliJ are:
Beta 44
4 44

The class code is:
public class Baap {
public int h = 4;
public int getH() {
System.out.println("Baap " + h);
return h; }
}
public class Baap {
public int h = 4;
public int getH() {
System.out.println("Baap " + h);
return h; }
}

Question: At (A) above, the 1st call is to b.h. The variable b is referring to the variable from class Baap and in Baap the h variable has a value of 4. Why is 4 not being the 1st value printed? Instead 'Beta' from the b.getH() method is the 1st value printed in the output.

Thanks,
Daniel

Re: Mock exam question

Posted: Sat Apr 10, 2021 10:22 am
by admin
This question has been discussed multiple times in detail. Please go through the following discussions and let me know if you still have doubts:
viewtopic.php?f=2&t=3214
and
viewtopic.php?f=2&t=2075