实例字段的继承如何在这个特定的代码中工作? [英] How does inheritance of instance fields work in this particular code?

查看:68
本文介绍了实例字段的继承如何在这个特定的代码中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class A
{
    int a = 2, b = 3;
    public void display()
    {
        int c = a + b;
        System.out.println(c);
    }
}
class B extends A
{
    int a = 5, b = 6;
}
class Tester
{
    public static void main(String arr[])
    {
        A x = new A();
        B y = new B();
        x.display();
        y.display();
    }
}

为什么输出为5,5?而不是5,11?。 y.display()方法如何工作?

Why does the output come out as 5,5? And not 5,11?.How would the y.display() method work?

推荐答案


为什么输出为5,5?

why does the output comes 5,5?

因为 A.display()只知道字段 Aa Ab 。这些是 A 中任何代码都知道的唯一字段。看起来您希望 B 中的声明覆盖现有的字段声明。他们没有。他们声明了隐藏现有字段的字段。变量实际上不像方法那样表现 - 覆盖变量的概念根本就不存在。来自 JLS第8.3节

Because A.display() only knows about the fields A.a and A.b. Those are the only fields that any code in A knows about. It looks like you expect the declarations in B to "override" the existing field declarations. They don't. They declare new fields which hide the existing fields. Variables don't behave virtually in the way that methods do - the concept of overriding a variable simply doesn't exist. From the JLS section 8.3:


如果类声明了具有特定名称的字段,那么该字段的声明将被称为 hide any和all accessible超类中具有相同名称的字段的声明,以及类的超接口。

If the class declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superclasses, and superinterfaces of the class.

您可以通过更改<$来获得所需的效果c $ c> B 以便它的构造函数改变它继承自 A 的现有字段的值:

You can get the effect you want by changing B so that its constructor changes the values of the existing fields that it inherits from A instead:

class B extends A {
    B() {
        a = 5;
        b = 6;
    }
}

请注意,这些不是变量声明。他们只是作业。当然在大多数代码中(好吧,我见过的大多数代码) A 中的字段都是私有的,因此无法从访问B ,但这仅仅是为了解释语言行为的例子。

Note that these are not variable declarations. They're just assignments. Of course in most code (well, most code I've seen anyway) the fields in A would be private, so couldn't be accessed from B, but this is just example for the purpose of explaining the language behaviour.

这篇关于实例字段的继承如何在这个特定的代码中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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