0

i have problem in my java project recently with generics. the following is the simplified version of my actual problem.

abstract class Value{
    public int value;

    Value(int v){ value = v; }
}

class Wrap<T> {
    T data;

    Wrap(T data){ this.data = data; }    

    public void add(T value){
        data = actualAdd(data, value);
    }

    public T actualAdd(T p1, T p2){/* other code. don't worry */}
}

easy to see, i want to inherit Value afterwards.

but when it comes to combine both, i.e.:

Wrap<? extends Value> wrapValue;

i really wish add recieves Value, i.e.:

wrapValue.add(Value value) 

instead of

wrapValue.add(? extends Value value)

since i just want to add up the value, the other fields are irrelevant.

i know how to do it in static method, that should be:

public static void staticAdd(Wrap<? extends T> wrapper, T value){/**/}

but how can i have the same trick in method member?

Jason Hu
  • 6,239
  • 1
  • 20
  • 41

1 Answers1

0

PECS (Producer Extends and Consumer Super) is the way to go here. Try using ? super Value.

Here is one post, which might help you with more context on this.

nitishagar
  • 9,038
  • 3
  • 28
  • 40