Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected output in inheritance

Tags:

java

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?

like image 910
birraa Avatar asked Mar 11 '23 03:03

birraa


2 Answers

The output consists of two parts:

  1. A line printed inside getH()
  2. A line printed inside 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.

like image 108
Sergey Kalinichenko Avatar answered Mar 15 '23 09:03

Sergey Kalinichenko


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.

like image 29
Eran Avatar answered Mar 15 '23 10:03

Eran