java - Same method in multiple classes but using different types -
i have multiple classes implement method create.
public teamscorepk create(teamscore entity) { teamscorepk pk = entity.getpk(); if (!pk.validate()) { throw new illegalargumentexception("part of primary key null:" + entity); } if (instances.containskey(pk)) { throw new illegalargumentexception(entity + " exists."); } instances.put(pk, entity); return pk; } map instances serves db table. difference between create method in different classes types uses. i'd put method abstract super class. problem map instances, because have extending classes. declare abstract method getinstances, have problem type of map should return. if use map<? extends pk, ? extends entity>, naturally , error when putting types pk , entity it.
could give me example or advice, how abstract class should like?
i make abstract superclass generic types of keys , values subclasses handle.
public abstract class somesuperclass<k extends pk, v extends entity> { then can place algorithm in concrete method.
public k create(v entity) { k pk = entity.getpk(); if (!pk.validate()) { throw new illegalargumentexception("part of primary key null:" + entity); } if (getinstances().containskey(pk)) { throw new illegalargumentexception(entity + " exists."); } getinstances().put(pk, entity); return pk; } public abstract map<k, v> getinstances(); } i have replaced instances getinstances(), abstract method subclasses implement.
public class teamscoresubclass extends somesuperclass<teamscorepk, teamscore> { then subclass has supply map (and populate somehow).
map<teamscorepk, teamscore> map = new hashmap<>; and
public map<teamscorepk, teamscore> getinstances() { return map; } }
Comments
Post a Comment