eccentricCoder
eccentricCoder

Reputation: 844

Why the Overrided function getting called first?

I executed the following program and I am curious about the output i got in which the function output is getting printed first even if it was the variable i tried to print first.

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());
    }

}

The output was as follows

Beta 44
4 44
Beta 44
44 44

Can somebody help me understand why the function block gets executed first?

Upvotes: 0

Views: 88

Answers (2)

Xvolks
Xvolks

Reputation: 2155

Your System.out.println line prints a String.

The String is evaluated at run-time as b.h + " " + b.getH(), so it concatenates b.h, space and the result of the method b.getH(), so it calls getH() which prints Beta 44, then prints the result 4 44.

Upvotes: 3

mhlz
mhlz

Reputation: 3547

When you call a function, all of its parameters have to be evaluated first. In your case the only parameter to System.out.println is the expression b.h + " " + b.getH().

Since that is still an expression, the next step is to evaluate that expression, which means to determine the value of the expression. It consists of 2 plus operators which have 3 operands. In order to evaluate the plus operators the program has to evaluate the values of the operands.

The value of b.h evaluates to 4, because variables are resolved statically-ish in Java. The type of the variable b is Baap so we get 4.
The next value is " " which is already a literal so there's nothing to do.
After that we have the function call b.getH(). Function calls in Java are always resolved virtually, so we actually call the function called getH of the Beta type. This function only sees its own scope, where the variable h declared in the class Beta "shadows" the one declared in the class Baap, meaning the h variable of Baap is hidden to every member of Beta.
To evaluate the function call we have to execute the function which prints "Beta 44" and returns the value 44.

Now that we have values for all 3 operators we can evaluate the expression with the + operators. This results in the String "4 44" which now gets passed to System.out.println and finally printed on the screen.

Upvotes: 0

Related Questions