Note that there are some explanatory texts on larger screens.

plurals
  1. POPossibly recursive Java generics between two classes
    primarykey
    data
    text
    <p>I'm attempting to produce some classes to control a model-view-presenter application. I've come up with the following definitions, but am struggling to avoid recursive generics.</p> <pre><code>public abstract class Presenter&lt;V extends View&lt;...?&gt;&gt; { protected V view; public Presenter(V view) { this.view = view; } // ... } public abstract class View&lt;P extends Presenter&lt;...?&gt;&gt; { protected P presenter; // ... } </code></pre> <p>I wanted to enforce a mutual relationship between the two classes. The idea being that I could instantiate a Presenter for a particular View, with both classes relying on useful methods defined in the abstract base classes, yet both knowing exactly what subclass of the counterpart abstract class is in use.</p> <p>My issues is the defining the <code>..?</code> part of the code. I can't see a way to avoid a recursive situation, such as:</p> <pre><code>public abstract class View&lt;P extends Presenter&lt;V&gt;, V extends View&lt;Q&gt;, Q extends...&gt; </code></pre> <p>and even that definition is not consistent, as the View class now takes two generic parameters... mass confusion.</p> <p>I basically wanted to avoid the classes being littered with references to the abstract class type, necessitating lots of casting throughout the concrete implementations, as below:</p> <pre><code>// simpler option public abstract class Presenter { protected View view; public Presenter(View view) { this.view = view; } } public class FooPresenter extends Presenter { public FooPresenter(BarView view) { super(view); } public someMethod() { ((BarView) getView()).viewSpecificMethod(); } } </code></pre> <p>Each concrete implementation of these classes would need to constantly cast from the abstract type to the type it "knows" is in use.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload