Feisty Otter
Feisty Otter

Reputation: 144

How to implements a wildcard argument properly?

I am trying to write a simple generic class Operations<T extends Number>, that has a single method T sum(). It is supposed to take any Number object and return its sum with T. I have a strong suspicion that I should use bounded wildcard argument, but I have no idea how to proceed.

interface OperationsInterface<T extends Number> {

    public T sum(Operations<? extends Number> v);

}

class Operations <T extends Number> 
    implements OperationsInterface<T> {

    private T o;

    public Operations(T o) {
        this.o = o;
    }

    @Override
    public T sum(Operations<? extends Number> v) {

    }

}

Upvotes: 2

Views: 121

Answers (2)

EpicPandaForce
EpicPandaForce

Reputation: 81529

If you don't want to bind the parameters to T then you can of course just do

interface OperationsInterface<T extends Number> {

    public <N extends Number> T sum(Operations<N> v);

}

class Operations <T extends Number> 
    implements OperationsInterface<T> {

    private T o;

    public Operations(T o) {
        this.o = o;
    }

    @Override
    public <N extends Number> T sum(Operations<N> v) {

    }

}

And see if that works for you.

Upvotes: 1

Branislav Lazic
Branislav Lazic

Reputation: 14806

You don't even need: ? extends Number as a type parameter of method parameter. Your interface can be like this:

interface OperationsInterface<T extends Number> {

    public T sum(T... t);

}

since you cannot pass type argument that's not a subclass of Number.

And your implementation class like this i.e.:

class Operations implements OperationsInterface<Integer> {

    @Override
    public Integer sum(Integer... t) {
        // do sum
        return null;
    }

}

Upvotes: 1

Related Questions