Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you want to avoid unchecked cast warnings from your compiler (and don't want to @SuppressWarnings("unchecked")), then you need to do a little more:</p> <p>First of all, your definition of Pet must be self-referential, because Pet is always a generic type:</p> <pre><code>abstract class Pet &lt;T extends Pet&lt;T&gt;&gt; </code></pre> <p>Secondly, the <code>(T) this</code> cast in setName is also unchecked. To avoid this, use the "getThis" technique in the excellent <a href="http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#FAQ206" rel="noreferrer">Generics FAQ by Angelika Langer</a>:</p> <blockquote> <p>The "getThis" trick provides a way to recover the exact type of the this reference.</p> </blockquote> <p>This results in the code below, which compiles and runs without warnings. If you want to extend your subclasses, then the technique still holds (though you'll probably need to genericise your intermediate classes).</p> <p>The resulting code is:</p> <pre><code>public class TestClass { static abstract class Pet &lt;T extends Pet&lt;T&gt;&gt; { private String name; protected abstract T getThis(); public T setName(String name) { this.name = name; return getThis(); } } static class Cat extends Pet&lt;Cat&gt; { @Override protected Cat getThis() { return this; } public Cat catchMice() { System.out.println("I caught a mouse!"); return getThis(); } } static class Dog extends Pet&lt;Dog&gt; { @Override protected Dog getThis() { return this; } public Dog catchFrisbee() { System.out.println("I caught a frisbee!"); return getThis(); } } public static void main(String[] args) { Cat c = new Cat(); c.setName("Morris").catchMice(); Dog d = new Dog(); d.setName("Snoopy").catchFrisbee(); } } </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