Reputation: 21
Ok, I have a base class for all my entites, lets call it BaseEntity. All other entity classes inherit form this one, so for example:
A extends BaseEntity { ... }
B extends BaseEntitay {
private A myA;
}
As you can see, one entity can have a relation to another entity. In fact, there is a hierachy, like D has C has B has A...
The problem: I want to create a class which will call a method on the objects of the diffrent base class types. The idea was to have a public method like this:
public BaseClass getLowerLayer(BaseClass entity) {
return getLowerLayer(entity);
}
And then in the same class all needed methods:
public B getLowerLayer(C entit) {
return someFancyMethod(entity); // this is defined elsewhere to get the right entity. I can not modify it.
}
But this does not work as it creates an infinity loop. Is there a way to create something like this (without instanceof) in a minimal invasive manner?
Upvotes: 1
Views: 59
Reputation: 36
I think I know what you mean. This is well if im not wrong a perfect example of polymorphism.
The fact that you are extending the base class to subclass makes you wonder how would the super class know that these subclass is the one extending him? I have one humble solution for that. I am not good in thorough explaining but I will give an example:
public abstract class AbstractDAO<T extends Serializable> {
protected EntityManager em;
protected Class<?> entityClass;
public AbstractDAO(EntityManager em, Class<?> c) {
this.em = em;
this.entityClass = c;
}
@SuppressWarnings("unchecked")
public T findById(Serializable id) {
if (id == null) {
throw new PersistenceException("id cannot be null");
}
return (T) em.find(entityClass, id);
}
}
public class CustomerDAO extends AbstractDAO<Customer> {
public CustomerDAO(EntityManager em) {
super(em, Customer.class);
}
}
public class OrderDAO extends AbstractDAO<Order> {
public OrderDAO(EntityManager em) {
super(em, Order.class);
}
}
Now as you can see I have extended my abstract class to my subclass and uses generic tags to let the super class know what subclass is he in.
EntityManager em = PersistenceManager.getEntityManager();
CustomerDAO customDAO = new CustomerDAO(em);
customDAO.findById(45325L);
"PersistenceManager" as assumed custom class I created.
Upvotes: 2