简体   繁体   中英

Require subclasses to set a parent class's data member

This seems like a common task but I got a little confused. Suppose I have an abstract parent class with a data member and corresponding getter/setter.

public abstract class Parent {

    private MyObj myObj;

    public MyObj getMyObj() { return myObj; }
    public void setMyObj(MyObj myObj) { this.myObj = myObj; }
}

I need to force the child classes to set the "myObj" variable. I have 2 options:

  1. Make the setter "abstract" (but not the getter). This seems weird to me, I haven't seen it before.
  2. Avoid declaring the data member in parent at all. Just have one parent method,

    abstract public MyObj getMyObj();

and then the parent will always refer as getMyObj().getField1(), getMyObj().getField2(), etc. Each time a new object is created, rather than storing it in a single place.

What's the standard way to force a child class to set a parent class's data variable? Is it a new abstract method, outside the getters/setters?

To have the compiler enforce that myObj is set, you can do this:

public abstract class Parent {

    private final MyObj myObj;

The final means the value cannot be changed, but also that it must be set. Since you have a setter, the value may be updated; if that's expected don't add the final keyword.

To make sure the field is set, add a constructor:

    protected Parent( MyObj initial ) {
        if ( initial == null )
            throw new IllegalArgumentException( "Must provide a value!" );
        this.myObj = initial;
    }

您可以从子对象中调用setter方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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