Trying to implement a generic and inheritance classes in a Java Project. For that reason I created the "Base" classes and Interfaces that will inheritance all the specific classes and interfaces.
I mean, I have a Base Interface
public interface BaseServices<T> {
public boolean validate(T item, int id) throws Exception;
}
And a Base Implementation for that Interface
public class BaseServicesImpl implements BaseServices<BaseBO> {
@Autowired
BaseDao dao;
CategoryBO bo;
public BaseServicesImpl()
{
this.bo = new CategoryBO();
}
@Override
public boolean validate(BaseBO item, int id) throws Exception {
return dao.validate("name",item.toString(), id);
}
}
Where BaseBO is the business object that ALL the other objects will extend.
And then, for an specific object, I will have a particular Interface which extends the Base one.
public interface CategoryServices extends BaseServices {
}
And its implementation:
public class CategoryServicesImpl extends BaseServicesImpl implements CategoryServices<CategoryBO> {
@Autowired
CategoryDao categoryDao;
public CategoryServicesImpl()
{
this.dao = categoryDao;
}
@Override
public boolean validate(CategoryBO item, int id) throws Exception {
return dao.validate("name",item.getName(), id);
}
}
Where some object can implement the generic "Validate" method (which validates just the name) or extend it to what the class requiredpublic class CategoryServicesImpl extends BaseServicesImpl implements CategoryServices.
How can I make this work? Is it possible? I'm trying to do the most I can to reuse my code. Let me know if there is another way.
EDITED: What I'm trying to do, is to have a base class with all the common method for all the classes, let say, the basic for create, edit, delete, get, getAll, etc. And then in each class I also can have and override for those method because in some classes they will be different, but in most, they will just do the same so it will call the generic ones that were defined in Base class.
You can easily achieve what you want, just with a couple of changes:
public interface BaseServices<T extends BaseBO> {
boolean validate(T item, int id) throws Exception;
}
public interface CategoryServices
extends BaseServices<CategoryBO> {
}
public class BaseServicesImpl<T extends BaseBO>
implements BaseServices<T> {
@Override
public boolean validate(T item, int id) throws Exception {
return true;
}
}
public class CategoryServicesImpl
extends BaseServicesImpl<CategoryBO>
implements CategoryServices {
@Override
public boolean validate(CategoryBO item, int id) throws Exception {
return true;
}
}
The key is to let your generic T type be a descendant of BaseBO, and then adjust your BaseServicesImpl class to also be generic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With