Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The reason why you can add objects of both type <code>A</code> and <code>B</code> is due to the fact that you parametized your XClass with the interface, so there is nothing wrong with adding two different classes that implement that interface.</p> <p>If, on the other hand, you had defined XClass as:</p> <pre><code>XClass&lt;A&gt; xc = new XClass&lt;A&gt;(); </code></pre> <p>then the expression <code>xc.add(b);</code> would give a compilation error, since all the objects added must have the same type as was declared, in this case, A.</p> <p>If you declare you <code>xc</code> as, for instance: </p> <p><code>XClass&lt;? extends AnInterface&gt; xc = new XClass&lt;AnInterface&gt;();</code></p> <p>Then it's not legal anymore to add <code>a</code> or <code>b</code>, since the only thing we know is that xc is of some unknown <strong>but fixed</strong> subtype of <code>AnInterface</code>, and there is no way to know if that unknown type is <code>A</code> or <code>B</code> or anything else.</p> <p>But let's say you're writing a method to accept a XClass type that you can iterate over the elements that were added before. Your only restriction (for the sake of the example), is that the items extend <code>AnInterface</code>, you don't care what the actual type is.</p> <p>You can declare this method like:</p> <pre><code>public static void dummyMethod(XClass&lt;? extends AnInterface&gt; dummy){ //do stuff here, all the elements extend (implement in this case), AnInterface, go wild. } </code></pre> <p>And now you can pass into this method anything like <code>XClass&lt;A&gt;</code>, <code>XClass&lt;B&gt;</code> or <code>XClass&lt;AnInterface&gt;</code>, and it will all be valid.</p> <p>Keep in mind that you can't add to the object you pass, for the same reason above. We don't know what the unknown type is!</p> <pre><code>public static void dummyMethod(XClass&lt;? extends AnInterface&gt; dummy){ //do stuff here, all the elements extend (implement in this case), AnInterface, go wild. dummy.add(new A()); //you can't do this, we have no idea what type ? stand for in this case } </code></pre>
 

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