简体   繁体   English

在 java 中使用构造函数 arguments 继承 class

[英]Inheriting a class with constructor arguments in java

The situation is I want to inherit an object to have a cleaner constructor interface:情况是我想继承一个 object 以获得更清晰的构造函数接口:

class BaseClass {
    public BaseClass(SomeObject object){
        ...
    }
}

class SubClass extends BaseClass{
    private SubObject subObject = new SubObject();
    public SubClass(){
        super(new SomeObject(subObject)); // doesn't compile
    }
}

But to do that I need to do stuff before the constructor like in the example above but can't because Java doesn't allow that.但要做到这一点,我需要像上面的例子一样在构造函数之前做一些事情,但不能因为 Java 不允许这样做。 Is there any way around this?有没有办法解决? I'm starting to feel that if your class is designed to be subclassed it should always implement default constructor and provide setters for the values it needs... Sometimes you can get away with this if you create a new object straight into the super constructor as an argument but if you need a reference to the object you created then you are hosed.我开始觉得,如果您的 class 被设计为子类,它应该始终实现默认构造函数并为其所需的值提供设置器......有时如果您直接在超级构造函数中创建一个新的 object作为一个论点,但如果您需要参考您创建的 object,那么您就完了。

You need to change it so that you're not referring to an instance member in the superconstructor call.您需要对其进行更改,以免在超构造函数调用中引用实例成员。 Unfortunately if you need to then "save" the SubObject , it becomes tricky.不幸的是,如果您需要“保存” SubObject ,它会变得很棘手。 I think you'd have to do it with constructor chaining:我认为您必须使用构造函数链接来做到这一点:

class SubClass extends BaseClass{
    private SubObject subObject;

    public SubClass() {
        this(new SubObject());
    }

    private SubClass(SubObject subObject) {
        super(new SomeObject(subObject));
        this.subObject = subObject;
    }
}
public SubClass(){
    super(new SomeObject(new SubObject())); // this should compile
}

Now in your super class, do something like this:现在在您的超级 class 中,执行以下操作:

private final SomeObject foo;
public BaseClass(SomeObject foo){
    this.foo = foo;
}
public /* or protected */ SomeObject getFoo(){return this.foo;}

Not exactly an answer since you would have no SubClass , but you could use a factory.不完全是答案,因为您没有SubClass ,但您可以使用工厂。

public BaseClassFactory {
    public static BaseClass newBaseClass() {
        // init some object
        // ...
        return new BaseClass(someObject);
    }
}

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

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