理解继承的基本Java代码 [英] basic java code to understand inheritance

查看:93
本文介绍了理解继承的基本Java代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么System.out.println(b.h + " " + b.getH());打印以下内容:

Beta 44 <br/>
4 44          (notice this is in the second line)

我希望它能打印出这样的内容:

I was expecting it to print something like this:

4 Beta 44 44   (this one is in one line)

之所以以这样的方式打印,是因为我们先调用b.h,即4,然后调用b.getH(),其将打印Beta 44 44

The reason why I thought it would print this way is because we call b.h first which is 4.Then we call b.getH() which will print Beta 44 44

这是代码:

class Baap{

        int h = 4;
        public int getH(){
                System.out.println("Beta " + h);
                return h;
        }
}

class Beta extends Baap{
        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());
        }

}

推荐答案

首先,对getH()的调用将显示"Beta 44",因为System.out.println(b.h + " " + b.getH())的参数是在调用println之前求值的.

First, the call to getH() prints "Beta 44", since the argument of System.out.println(b.h + " " + b.getH()) is evaluated before println is called.

然后System.out.println(b.h + " " + b.getH())打印"4 44".

Then System.out.println(b.h + " " + b.getH()) prints "4 44".

b.h返回4,因为没有覆盖实例变量,并且由于b的编译时间类型为Baap,因此b.h返回超类的实例变量.

b.h returns 4 because there is no overriding for instance variables, and since b's compile time type is Baap, b.h returns the instance variable of the super class.

b.getH()返回44,因为您b的运行时类型是Beta,它将覆盖getH().

b.getH() returns 44 because you b's runtime type is Beta, which overrides getH().

这篇关于理解继承的基本Java代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆