Why the Overrided function getting called first?

杀马特。学长 韩版系。学妹 提交于 2019-12-20 07:36:02

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/35727305/why-the-overrided-function-getting-called-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!