Note that there are some explanatory texts on larger screens.

plurals
  1. POHow would I use generics in Java to create a generic interface that defines a method that only accepts the implementation as a parameter?
    primarykey
    data
    text
    <p>Is there a way to define a method in an interface where implementations can be typed to the implementing class? Here's a concrete example of my initial attempt to solve it, but I'll point out where it fails.</p> <pre><code>public interface ErrorMeasurable&lt;T extends ErrorMeasurable&lt;T&gt;&gt; { // I want every implementation of this method to accept // the implementing type as a parameter. I'm willing to accept // that programmers can maliciously type it to something else // that meets the type boundary. I'm not willing to accept // polymorphic usage to be verbose or strange as the below example shows. boolean approxEquals(T that); } // This works... public class MyDecimal implements ErrorMeasurable&lt;MyDecimal&gt; { boolean approxEquals(MyDecimal that) { ... } } // But polymorphism doesn't work well... public interface MyNumber&lt;T extends ErrorMeasurable&lt;T&gt;&gt; implements ErrorMeasurable&lt;T&gt; { boolean approxEquals(T that) { ... } } public class MyDecimal2 implements MyNumber&lt;MyDecimal&gt; { boolean approxEquals(MyDecimal that) { ... } } public class UsesNumbers { // PROBLEM 1: the type parameter is unbound. MyNumber rawNumber1, rawNumber2; // PROBLEM 2: This binds the type parameter but it is hard to understand why its typed to itself MyNumber&lt;MyNumber&gt; boundNumber1, boundNumber2; void example() { // PROBLEM 3: There will be a compiler warning about the raw types. rawNumber1.approxEquals(rawNumber2); // Works without warnings, see PROBLEM 2 though. boundNumber1.approxEquals(boundNumber2); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    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.
 

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