I got a certain code from Java certification question and its output kind of baffled me. Here is the code
class Baap {
public int h = 4;
public int getH() {
System.out.println("Baap " + h);
return h;
}
}
class Beta extends Baap {
public int h = 44;
public int getH() {
System.out.println("Beta " + h);
return h;
}
public static void main(String[] args) {
Baap b = new Beta();
System.out.println(b.h + " " + b.getH());
}
}
The output is:
Beta 44
4 44
I was expecting it to be:
4 Beta 44
44
Why does it produce this output?
The output consists of two parts:
getH()
main()
The line produced by getH() is printed before the line produced by main(), because getH() must finish before main finishes constructing its output.
Now the output should be clear: even though 4 is evaluated before the call to getH is made inside main, it gets printed after getH() has returned.
Before System.out.println(b.h + " " + b.getH()) can print anything, b.h + " " + b.getH() must be evaluated.
b.getH() calls Beta's method (since it overrides the base class method) which prints Beta 44.
Then b.h (4) is appended to the result of b.getH() (44) and println prints 4 44.
b.h returns the value of the h variable of the base class (4), since the compile time type of b is Baap (the base class), and variables cannot be overridden. On the other hand, b.getH() returns the value of the h variable of the sub-class (44), since methods can be overridden.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With