从子类对象访问超级字段 [英] Access super field from subclass object

查看:77
本文介绍了从子类对象访问超级字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个奇怪的问题,但是我不明白我是如何设法使它起作用的.我的意图是从覆盖该字段的对象访问超级字段.首先,什么起作用(1):

This may be a strange question, but I don't understand how have I managed to get this to work. My intention was to access the super's field from an object that overrides the field. First, what did work (1):

class Foo {
    protected int i = 0;

}

public class Bar extends Foo {
    int i = 1;
    Foo f() {
        return this;
    }
    public static void main (String[] args) {
        Bar b = new Bar();
        System.out.println(b.i);
        System.out.println(b.f().i);
    }
}

我首先尝试使用(2)之类的东西:

I first tried to use something like (2):

System.out.println(b.super.i);

这不起作用.然后,我尝试使用(3):

which didn't work. I then tried to use (3):

Foo f() {
    return super;
}

那也不起作用.

因此,请参考上面的编号部分:

So, referring to the numbered parts above:

  1. 为什么return this强制转换为Foo返回对b.super对象的引用?
  2. main中,我以为b.super是实例化对象"b"的超级引用的引用.有什么方法可以从包含的对象访问对超级对象的引用?也许是从反射中得到的东西,但是我不想访问.class对象(b.getClass().getSuper()),而是希望访问b中包含的实例化Foo.
  3. 为什么return.super不返回对b.super对象的引用?
  1. Why does return this cast to Foo return a reference to the b.super object?
  2. In main, I would have thought b.super would be the reference to the instantiated object "b" 's super reference. Is there any way to access the reference to the super object from the containing object? Maybe something from reflection, but I don't want access to the .class object (b.getClass().getSuper()), but rather the instantiated Foo contained within b.
  3. Why does return.super not return a reference to the b.super object?

推荐答案

我的意图是从覆盖该字段的对象访问超级字段.

My intention was to access the super's field from an object that overrides the field.

您没有覆盖"该字段.您正在创建另一个不相关的同名字段.产生的名称冲突是您遇到困难的直接原因.

You are not "overriding" the field. You are creating a second, unrelated field with the same name. The resulting name clash is the direct cause of your difficulty.

如果两个字段不相关,请给它们提供不同的名称.

If the two fields are unrelated, give them different names.

反之,如果您试图实现多态行为,请将其转换为方法:

If, on the other hand, you are trying to achieve polymorphic behaviour, turn them into methods:

class Foo {
    protected int get_i() { return 0; }
}

public class Bar extends Foo {
    @Override
    protected int get_i() { return 1; }
}

这篇关于从子类对象访问超级字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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