覆盖子类中的成员数据,用于超类实现? [英] Override member data in subclass, use in superclass implementation?

查看:111
本文介绍了覆盖子类中的成员数据,用于超类实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,是否可以覆盖子类中的成员数据并将该重写版本作为超类实现中使用的数据?

In Java, is it possible to override member data in a subclass and have that overridden version be the data used in a super class's implementation?

换句话说,这就是我想要发生的事情,并且它没有发生:

In other words, here's what I am trying to get to happen, and it's not happening:

abstract public class BasicStuff {
        protected String[] stuff = { "Pizza", "Shoes" };

        public void readStuff() {
                for(String p : stuff) { 
                        system.out.println(p); 
                }
        }
}

..

public class HardStuff extends BasicStuff {
        protected String[] stuff = { "Harmonica", "Saxophone", "Particle Accelerator" };
}

此调用:

HardStuff sf = new HardStuff();
sf.readStuff();

...打印披萨。我想让它打印后者。

... prints Pizza and Shoes. I want it to print the latter instead.

我认识到这是一个相当差的等级OO练习;我需要它来处理一个非常具体的情况,因为我正在使用XML配置和反射。

I recognise that this is rather poor hierarchical OO practice; I needed it for a very specific case as I am doing something with XML configuration and reflection.

是否有一个修饰符可以实现这一点?

Is there a modifier that can make this happen?

是的,我确实认识到有一些包装可以用来解决我的子类中的这个问题,即通过指示 stuff [] 现在存储在具有不同名称的数组中。我只是想保持这个简单,原则上很好奇。

And yes, I do recognise that there are wrappers one can use to get around this problem in my subclass, i.e. by indicating that the contents of stuff[] are now stored in an array with a different name, for instance. I'm just trying to keep this simple, and am curious in principle.

提前多多谢谢!

推荐答案

我相信你必须设置一个访问方法,即使用:

I believe you must interpose an accessor method, i.e., use:

    for(String p : getStuff()) { 

在超类中,并添加:

    protected String[] getStuff() { return stuff; }

只要你有 protected String []东西重新定义。

覆盖确实适用于方法,而不是数据(至少在Java模型中是这样;其他一些语言也是如此)事情不同),所以要获得覆盖效果,你必须插入一个方法(通常是一个简单的访问器,像这里)。它根本不会使事情变得复杂,它只是一种非常简单的方式来指示Java编译器本质上使用您期望的行为所需的额外级别的间接。

Overriding really applies to methods, not data (at least, that is so in the Java model; some other languages do things differently), and so to get the override effect you must interpose a method (typically a dirt-simple accessor, like here). It doesn't really complicate things at all, it's just a very simple way to instruct the Java compiler to use, intrinsically, the "extra level of indirection" that your desired behavior requires.

这篇关于覆盖子类中的成员数据,用于超类实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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