如何创建一个“抽象字段”? [英] How to create an "abstract field"?

查看:225
本文介绍了如何创建一个“抽象字段”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道抽象字段在java中不存在。我也阅读了这个问题,但提出的解决方案不会解决我的问题。也许没有解决方案,但它是值得问:)

I know abstract fields do not exist in java. I also read this question but the solutions proposed won't solve my problem. Maybe there is no solution, but it's worth asking :)

我有一个抽象类在构造函数中的操作,具体取决于其中一个字段的值。
问题是此字段的值会根据子类而改变。
我如何做,操作是对子类重新定义的字段的值完成?

I have an abstract class that does an operation in the constructor depending on the value of one of its fields. The problem is that the value of this field will change depending on the subclass. How can I do so that the operation is done on the value of the field redefined by the subclass ?

如果我只是覆盖子类操作是对抽象类中的字段的值完成的。

If I just "override" the field in the subclass the operation is done on the value of the field in the abstract class.

我可以任何解决方案,确保操作将完成在子类的实例化(即将操作放在构造函数中每个子类调用的方法中不是有效的解决方案,因为有人可能会扩展抽象类并忘记调用该方法)。

I'm open to any solution that would ensure that the operation will be done during the instantiation of the subclass (ie putting the operation in a method called by each subclass in the constructor is not a valid solution, because someone might extend the abstract class and forget to call the method).

此外,我不想将该字段的值作为构造函数的参数。

Also, I don't want to give the value of the field as an argument of the constructor.

解决方案,还是应该改变我的设计?

Is there any solution to do that, or should I just change my design ?

我的子类实际上是我的主程序使用的一些工具,所以构造函数必须是public的,并且它们将被调用的参数:

My subclasses are actually some tools used by my main program, so the constructor has to be public and take exactly the arguments with which they will be called:

tools[0]=new Hand(this);
tools[1]=new Pencil(this);
tools[2]=new AddObject(this);

(子类是Hand,Pencil和AddObject,它们都扩展了抽象类工具)

(the subclasses are Hand, Pencil and AddObject that all extend the abstract class Tool)

这就是为什么我不想改变构造函数。

That's why I don't want to change the constructor.

我要使用的解决方案是稍微改变上面的代码:

The solution I'm about to use is to slightly change the above code to:

tools[0]=new Hand(this);
tools[0].init();
tools[1]=new Pencil(this);
tools[1].init();
tools[2]=new AddObject(this);
tools[2].init();

并使用抽象getter来访问该字段。

and use an abstract getter to acces the field.

推荐答案

如何抽象getter / setter for field?

How about abstract getter/setter for field?

abstract class AbstractSuper {
    public AbstractSuper() {
        if (getFldName().equals("abc")) {
            //....
        }
    }

    abstract public void setFldName();
    abstract public String getFldName();
}

class Sub extends AbstractSuper {
    @Override
    public void setFldName() {
        ///....
    }

    @Override
    public String getFldName() {
        return "def";
    }
}

这篇关于如何创建一个“抽象字段”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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