1

Can I somehow partially implement a bunch of generics of a single class? What I would like to achieve is that I can accept a generic only when somone really relies on that type. See the following foo/bar example for a demonstration purpose of what I am looking for:

import java.util.Date;

public class Sample {
    public static abstract class ASomeFunc<AK, AV, PK, PV> {

        public void forwardTo(ASomeFunc<?, ?, PK, PV> lala) {

        }

        // EDIT 1:
        // we do some logic here and then pass a map entry to an actual implementation
        // but somethimes I do not care what the key is I am just interested in what the value is
        // public abstract Map.Entry<PK, PV> compute(Map.Entry<AK, AV> data);
    }

    public static class SomeFunc2 extends ASomeFunc<Date, String, Number, Number> {

    }


    // what I would like to do:
    // public static class SomeOtherFunc extends ASomeFunc<?, Number, ?, Number> {
    // but I ony can:
    public static class SomeOtherFunc extends ASomeFunc<Object, Number, Object, Number> {

    }

    public static void main(String[] args) {
        // but this now clashes ... sinc object is explicitly defined
        new SomeFunc2().forwardTo(new SomeOtherFunc());
    }
}
KIC
  • 5,887
  • 7
  • 58
  • 98
  • 2
    Are you looking for the equivalent of 'template specialization' in C++? If positive, prepare to be disappointed. Search for "type erasure Java generics" – Adrian Colomitchi Sep 29 '16 at 10:10
  • 2
    Why would a subclass not rely on that type? Might the abstract class be too specialised? – Will Sep 29 '16 at 10:13
  • 1
    Actually it doesn't compile because according to `forwardTo` and the type of `SomeFunc2`, `SomeOtherFunc` is expected to be of type `ASomeFunc, ?, Number, Number>` while its 2 last parameter types are `Object` and `Number` – Nicolas Filotto Sep 29 '16 at 10:30

1 Answers1

1

? would not work either, the second to last type argument would have to be exactly Number (since generics are invariant).

You might be able to get around it with some unchecked casts (an ugly solution). Or if, PK is a consumer type, use:

forwardTo(ASomeFunc<?, ?, ? super PK, PV> lala)

Which will also make your example compile. (See also, PECS)

But what your case implies is that you're only implementing part of the interface of ASomeFunc with your subclass.

In that case you should really try to split up the interface of ASomeFunc so that each subclass can choose exactly what they need to implement, but nothing more.

Community
  • 1
  • 1
Jorn Vernee
  • 31,735
  • 4
  • 76
  • 93
  • yes I am only implementing one opart of an interface. Sadly this interface operates on a `Map.Entry` but somethimes i just do not care about the key but just consume the value. See my edit in the code snipped. – KIC Sep 29 '16 at 11:21