Understanding generics: Incompatible types when class has generic type and implements one of its parametrised superclass

Viewed 625

I am implementing a simple app with MVP architecture.

Here are my MvpView and MvpPresenter interfaces (nothing interesting about MvpModel, so I am skipping it):

/// MvpView.java
public interface MvpView {
}

/// MvpPresenter.java
public interface MvpPresenter<V extends MvpView> {
    void attachView(V view);

    void detachView();
}

Now I have a basic MvpView implementation, which is an Activity:

// BaseActivity.java
public abstract class BaseActivity<V extends MvpView, P extends MvpPresenter<V>> 
        extends AppCompatActivity implements MvpView {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getPresenter().attachView(this);
    }

    public abstract P getPresenter();

    // other logic
}

As for me everything looks correct, but there is a compile error in line:

    getPresenter().attachView(this);

incompatible types

If I add cast to V then project compiles and everything works fine:

    getPresenter().attachView((V) this);

1. The question is why I need this cast or why I am experiencing this incompatible types error without casting?

(1 is already answered by Eran)

2. How I can link V to BaseActivity in this example or how it is better to implement this MVP approach?

It is strange, as for me, because my BaseActivity is extending MvpView as it is defined by this generic parameter: V extends MvpView!

2 Answers
Related