When I run this program:
class Baap {
public int h = 4;
public int getH() {
System.out.println("Baap " + h);
return h;
}
}
public 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());
Beta bb = (Beta) b;
System.out.println(bb.h + " " + bb.getH());
}
}
I get the following output:
Beta 44
4 44
Beta 44
44 44
If you look carefully at the first System.out.println(b.h + " " + b.getH());, doesn't this command tell Java to print out the value of h before the value of the getH() method?
Shouldn't the first part of the printout be 4 instead of Beta 44?
Before println is called, its argument - b.h + " " + b.getH() - is evaluated. During that evaluation Beta 44 is printed due to the call to getH(). Only after the evaluation, println is passed the result of the evaluation (4 44) and prints it.
Shouldn't the first part of the printout be 4 instead of Beta 44?
No because calling getH() first calls
System.out.println("Beta " + h);
then
return h;
which then allows the rest of the calling line
System.out.println(b.h + " " + b.getH());
to be evaluated.
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