简体   繁体   中英

Forcing Java attribute type in sub-class

I´ve got a question about inheritance/force certain value to an attribute in Java I am not sure about, even I spend a lot of time thinking about it. I will try to be as simple as possible.

So I´ve got an abstract class Foo , which has the Lombok annotation @Data :

@Data
public abstract class Foo{

private String id;
protected BoundType type;

public abstract void setBoundType(BoundType boundType);
}

Here is the enum BoundType :

public enum BoundType {

    IN, OUT;
}

And I´ve got another two classes, InFoo and OutFoo that extend Foo . The boundType of InFoo should always be the enum type IN . On the other side, the boundType in OutFoo should always be the enum type OUT . For instance:

@Data
public class InFoo extends Foo{

public void setBoundType() {
    //ALWAYS HAS TO BE BoundType.IN
 }
}

How can I enforce this? Not sure how to design it. Thanks in advance.

Make sure the constructor sets the correct value for each subclass, and then make sure there's no setter, so that there's no way to alter the value.

Also, see this post Omitting one Setter/Getter in Lombok on how to omit the setter for the BoundType field.

The correct value should be set in the constructor of the subclasses:

public InFoo() {
    boundType = BoundType.IN;
}

If it is necessary to use the setter pattern, you can perform a check, there:

public void setBoundType(BoundType boundType) {
    if(boundType != BoundType.IN)
        throw new IllegalArgumentException();
    this.boundType = boundType; // This line is actually unnecessary
}

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