Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I do not think you can enforce this at compile time. Please look at the workaround which ensures this at run time.</p> <pre><code>class Tester { public static void main(String[] args) { SnowLion lion = new SnowLion(); // This will throw IllegalArgumentException Bear bear = new Bear(); } } abstract class Animal&lt;T extends Animal&lt;T&gt;&gt; { protected Animal(Class&lt;T&gt; implClazz) { if (!implClazz.isAssignableFrom(getClass())) { throw new IllegalArgumentException(); } } abstract void partner(T other); } class Lion extends Animal&lt;Lion&gt; { public Lion() { super(Lion.class); } int areaUnderControl; @Override public void partner(Lion other) { this.areaUnderControl += other.areaUnderControl; } } class Human extends Animal&lt;Human&gt; { public Human() { super(Human.class); } int money; @Override public void partner(Human other) { this.money += other.money; } } class Bear extends Animal&lt;Lion&gt; { public Bear() { super(Lion.class); } int honey; @Override public void partner(Lion other) { this.honey += other.areaUnderControl; // Problem } } class SnowLion extends Lion { int snowAreaUnderControl; public SnowLion() { super(); } @Override public void partner(Lion other) { this.snowAreaUnderControl += other.areaUnderControl; } } </code></pre> <p>I got this idea from <a href="https://stackoverflow.com/questions/1627581/java-generics-to-enforce-return-type-of-abstract-method/1627633#1627633">Java generics to enforce return type of abstract method</a></p> <p>Hope this helps. </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