1

I have an abstract class that contains a map variable, and for the subclasses that extend the abstract class, I want to initialize the map using different implementations.

For example:

public abstract class Abs() {
    protected Map<Object, Object> map;
}

public class classA extends Abs {
    public classA() {
        map = new HashMap<>();
    }
}

public class classB extends Abs {
    public classB() {
        map = new ConcurrentHashMap<>();
    }
}

public class classC extends Abs {
    public classC() {
        map = new LinkedHashMap<>();
    }
}

My question is: Is there a current design pattern for this kind of implementation? Also because in the abstract class, we do not initialize the map, is there any concerns for that?

Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
Yiwei
  • 89
  • 8
  • What if a subclass doesn't assign an instance to `map`? Would that affect the superclass? If yes, then you need to re-think your contract. – ernest_k Apr 23 '19 at 15:15
  • Yes that's exactly my concern, that means we are forced to initialize the map in the subclass constructor now. Or is that ok if I initialize the map in the abstract class constructor, and in subclass just override that map with needed implementation? – Yiwei Apr 23 '19 at 15:25

1 Answers1

1

To force each subclass to provide a map instance, you can simply require them to supply it as a constructor argument:

public abstract class Abs {

    private Map<Object, Object> map;

    protected Abs(Map<Object, Object> map) {
        this.map = map;

        //you can even validate:
        if(null == this.map) throw new IllegalArgumentException("...");
    }
}

public class classA extends Abs {
    public classA() {
        super(new HashMap<Object, Object>());
    }
}

//all other subclasses follow the same logic
ernest_k
  • 44,416
  • 5
  • 53
  • 99