Can I define the Negatable interface in Java?

Actually, yes. Not directly, but you can do it. Simply include a generic parameter and then derive from the generic type.

public interface Negatable<T> {
    T negate();
}

public static <T extends Negatable<T>> T normalize(T a) {
    return a.negate().negate();
}

You would implement this interface like so

public static class MyBoolean implements Negatable<MyBoolean> {
    public boolean a;

    public MyBoolean(boolean a) {
        this.a = a;
    }

    @Override
    public MyBoolean negate() {
        return new MyBoolean(!this.a);
    }

}

In fact, the Java standard library uses this exact trick to implement Comparable.

public interface Comparable<T> {
    int compareTo(T o);
}

Leave a Comment