简体   繁体   English

在Java的子类中使用父变量的扩展版本

[英]Using an extended version of a parent variable in a child class in Java

I have an extending class which needs to use and extended version of a variable in the parent class. 我有一个扩展类,需要在父类中使用变量的扩展版本。 So far I've been getting away with using it like this: 到目前为止,我一直在像这样使用它:

public class ParentClass
{
    protected ParentVariable variable;

    public ParentClass(){
        this.variable = new ParentVariable();
    }
    ....
}

public class ChildClass extends ParentClass
{
    public ChildClass(){
        super();
        this.variable = new ChildVariable();
        //Where ChildVariable Extends ParentVariable
        ....
    }
}

This more or less works so long as every time I use variable I cast it to ChildVarible but this is ugly and throws up some issues. 只要每次使用变量,我都会将其强制转换为ChildVarible,但这或多或少起作用,但这很丑陋,并引发了一些问题。 Is there a better way to perform this? 有更好的方法来执行此操作吗? Thanks. 谢谢。

If it's possible to make your superclass abstract, you could solve this by using generics: 如果可以将您的超类抽象化,则可以使用泛型来解决:

public abstract class ParentClass<T extends ParentVariable>
{
    private T variable;

    protected T getVariable(){
        return variable
    }

    protected void setVariable(T variable){
        this.variable = variable;
    }
    ....
}

public class ChildClass extends ParentClass<ChildVariable>
{
    public ChildClass() {
        setVariable(new ChildVariable());
        //Where ChildVariable Extends ParentVariable
        ChildVariable foo = getVariable() // no cast nessecary
    }
}

Notice that I made your field private. 请注意,我将您的字段设为私有。 You should always access field by getter and setter methods, even in subclasses. 即使在子类中,也应始终通过getter和setter方法访问字段。

If this is not possible (maybe even if it was) it is an indicator that your design is flawed. 如果这不可能(即使可能),则表明您的设计存在缺陷。 Refactoring of all for classes might be needed to achieve a clean architecture. 为实现干净的体系结构,可能需要对类进行全部重构。 Unfortunately this depends on the whole implementation of all four classes and possibly the whole context those classes are used in. An answer to that would be too broad for stackexchange. 不幸的是,这取决于所有四个类的整个实现以及可能使用了这些类的整个上下文。对此的回答对于stackexchange而言可能太广泛了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM