An unexpected conclusion in inheritance

I have specific code from a Java certification question, and its output look puzzled 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());
    }
}

Conclusion:

Beta 44
4 44

I expected this to be:

4 Beta 44
44

Why is he making this conclusion?

+4
source share
4 answers

The output consists of two parts:

  • String printed inside getH()
  • String printed inside main()

The line created getH()is printed before the line created main()because it getH()must end before main, ending the construction of its output.

Now the conclusion should be clear: even if it 4is evaluated before the call getHis made inside main, it will be printed after it getH()returns.

+3
source

System.out.println(b.h + " " + b.getH()) -, b.h + " " + b.getH() .

b.getH() Beta ( ), Beta 44.

b.h (4) b.getH() (44) println 4 44.

b.h h (4), b Baap ( ), . , b.getH() h (44), .

+3

JLS:

15.7.2.

Java , ( &, ||, ?:) , .

getH() , , , , .

As there are two parts:

String baapBetaStr = b.h + " " + b.getH();

A) string concatenation

B) method call

And, of course, to combine this line, all parts of this expression must first be evaluated ("run")!

+1
source
public static void main(String[] args) {
        Baap b = new Beta();
        System.out.print(b.h + " ");
        System.out.print(b.getH());
    }
0
source

Source: https://habr.com/ru/post/1667121/


All Articles