Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>public interface MeterValue {} public class MeterValueA implements MeterValue {} public class MeterValueB implements MeterValue {} public interface ReportBuilder&lt;T extends MeterValue&gt; { void desiredMethod(); } public class ReportBuilderA implements ReportBuilder&lt;MeterValueA&gt; { @Override public void desiredMethod() {} } public class ReportBuilderB implements ReportBuilder&lt;MeterValueB&gt; { @Override public void desiredMethod() {} } void f() { ReportBuilder&lt;? extends MeterValue&gt; reportBuilder = null; if (Math.random() &gt; 0.5) reportBuilder = new ReportBuilderA(); else reportBuilder = new ReportBuilderB(); reportBuilder.desiredMethod(); } </code></pre> <p>Where: <code>ReportBuilder&lt;? extends MeterValue&gt;</code> means generic parameter can extend <em>MeterValue</em> interface.</p> <p>See <a href="http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html" rel="nofollow">tutorial</a> to read more explanations about the wildcard declaration.</p> <hr> <p>Note: please review this code in your particular case to avoid <a href="http://sourcemaking.com/refactoring/parallel-inheritance-hierarchies" rel="nofollow">Parallel inheritance</a> smell. If to add some new MeterValue you should add ReportBuilder it should mean you have probably this problem.</p> <hr> <p><strong>EDIT:</strong></p> <p>You cannot pass array with subtypes of MeterValue to ReportBuilderA which requeires at least MeterValueA. It is not type safe technic. Instantiate concrete class after inheritance is more appropriate for C++. In Java it is better do not change restricted type after inheritance.</p> <p>Probable solution, maybe applicable for your concrete case:</p> <p>1) Use single interface for MeterValue. All differences move to ReportBuilder inheritance. This means you have the parallel inheritance in your project.</p> <p>2) Use concrete <code>List&lt;MeterValueA&gt;</code> when call <code>getStuff()</code> method. All shared logic for processing <code>List&lt;MeterValueA&gt;</code> and <code>List&lt;MeterValueB&gt;</code> move to methods with signature: <code>public void sharedLogic(List&lt;? extends MeterValue&gt; list)</code></p>
 

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