Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Java supports covariant return types, so that's one option. Take advantage of the fact that both <code>A</code> and <code>B</code> are derived from <code>Object</code>:</p> <pre><code>public interface I { Object getSelf(); // or I, see below } public class A implements I { A getSelf() { return this; } } public class B implements I { B getSelf() { return this; } } </code></pre> <p>The point is that both <code>A.getSelf()</code> and <code>B.getSelf()</code> are legitimate overrides of <code>I.getSelf()</code>, even though their return type is different. That's because every <code>A</code> can be treated <em>like</em> an <code>Object</code>, and so the return type is <em>compatible</em> with that of the base function. (This is called "covariance".)</p> <p>In fact, since <code>A</code> and <code>B</code> are also known to derive from <code>I</code>, you can replace <code>Object</code> by <code>I</code> for the same reasons.</p> <p>Covariance is generally a Good Thing: Someone who has an interface object of type <code>I</code> can call <code>getSelf()</code> and get another interface, and that's all she needs to know. On the other hand, someone who already knows he has an <code>A</code> object can call <code>getSelf()</code> and will actually get another <code>A</code> object back. The additional information can be used to get a more specific derived type, but someone who lacks that information still gets everything that's prescribed by the interface base class:</p> <pre><code>I x = new A(); A y = new A(); I a = x.foo(); // generic A b = y.foo(); // we have more information, but b also "is-an" I A c = (A)x.foo(); // "cheating" (we know the actual type) </code></pre>
    singulars
    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.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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