2

I'm trying to implement my app with the MVP (Model-View-Presenter) pattern in Android but I'm facing a problem. I want to have an abstract base presenter with a view class property that is of a generic type ViewInterface but when creating a real presenter I'd like this property to be of the type RealPresenterView and if possible without needing to override the same function in all presenters.

As I probably didn't explain myself properly here's a bit of code to illustrate the case, first the base presenter:

abstract public class BasePresenter { protected ViewInterface view; protected ViewInterface getView() { return view; } } 

then the real presenter

public class RealPresenter { protected RealPresenterView view; // ... view.methodOnlyExistingInRealPresenterView(); } 

I wanted to be able to use the view in RealPresenter as RealPresenterView without needing to add much code in the class. Is that possible?

I've read about class templates but I haven't seen how to implement in this case without adding functions in every presenter.

1 Answer 1

4

You can use generics :

BasePresenter

abstract public class BasePresenter<T extends ViewInterface> { protected T view; protected T getView() { return view; } } 

RealPresenter

public class RealPresenter extends BasePresenter<RealPresenterView> { } 

Note that I didn't code in java for some time, but I think that's ok.

Sign up to request clarification or add additional context in comments.

2 Comments

mmm could be that <T implements ViewInterface> is <T extends ViewInterface>, this syntax gives me an error but if I change that looks like it works
yep, that's it!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.