解释变量隐藏在这个Java代码中是如何工作的 [英] Explain how variable hiding is working in this Java code

查看:110
本文介绍了解释变量隐藏在这个Java代码中是如何工作的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的代码

class A
{
    int x = 5;
    void foo()
    {
        System.out.println(this.x);
    }
}
class B extends A
{
    int x = 6;
    // some extra stuff
}
class C
{
    public static void main(String args[])
    {
         B b = new B();
         System.out.println(b.x);
         System.out.println(((A)b).x);
         b.foo();
    }
 }  

该计划的输出是

6
5
5

我理解前两个但是无法理解最后一个。 b.foo()如何打印5.B类将继承foo方法。但它不应该打印b.x会打印什么?究竟发生了什么?

I understand the first two but can't get my head around the last one. How does b.foo() print 5. B class will inherit the foo method. But shouldn't it print what b.x would print? What exactly is happening here?

推荐答案

是的, B 类继承 foo 方法。但 B 中的变量 x 隐藏了 x 中的 A ;它不会取代它。

Yes, the B class inherits the foo method. But the variable x in B hides the x in A; it doesn't replace it.

这是一个范围问题。 A 中的 foo 方法只能看到范围内的变量。范围中唯一的变量是 A 中的实例变量 x

This is an issue of scope. The foo method in A sees only the variables that are in scope. The only variable in scope is the instance variable x in A.

B 中继承 foo 方法,但不会覆盖该方法。如果您使用相同的代码显式覆盖 foo

The foo method is inherited, but not overridden, in B. If you were to explicitly override foo with the same exact code:

class B extends A
{
    int x = 6;

    @Override
    void foo()
    {
        System.out.println(this.x);
    }
}

然后提到的范围内的变量通过 this.x B x ,将打印 6 。虽然方法的文本是相同的,但由于范围的原因,引用是不同的。

Then the variable that would be in scope when referred to by this.x would be B's x, and 6 would be printed. While the text of the method is the same, the reference is different because of scope.

顺便提一下,如果你真的想引用 A 's x B 类中,你可以使用 super .x

Incidentally, if you really wanted to refer to A's x in the B class, you can use super.x.

这篇关于解释变量隐藏在这个Java代码中是如何工作的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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