3

I am having some trouble grasping generics. I've read through Oracle's tutorial on generics and it doesn't seem to address my question. I also don't know what to search for in finding my answer.

Let's say that I have the following code:

public abstract class Buff<V> {
    public V value;
{

public interface Buffable<V> {
    public void buff(Buff<V extends Buff> buff);
}

public class DoubleBuff extends Buff<double> {
    public double value;
}

public class DoubleBuffable implements Buffable<DoubleBuff> {
    public void Buff(DoubleBuff buff) {
        //implementation
    }
}

I want to be able to create classes that inherit Buff and have the member "value," but specify value's type (See DoubleBuff). I also want to define classes that implement the buff method using an input parameter that is of a subtype of Buff.

DoubleBuffable is some class that implements Buffable, but expects an input of DoubleBuff and not StringBuff.

Am I expressing my generics correctly?

2 Answers 2

5

Firstly, syntax. The declaration:

public interface Buffable<V> {
    public void buff(Buff<V extends Buff> buff);
}

Should be:

public interface Buffable<V extends Buff> {
    public void buff(Buff<V> buff);
}

The type variable you want, should be specified in the class declaration.

But you say:

I also want to define classes that implement the buff method using an input parameter that is of a subtype of Buff.

This way, the below declaration would suit your statement better:

public interface Buffable<V extends Buff<?>> {
    public void buff(V buff);
}

You may want to change that <?> part if you need a more specific type of Buff.

Lastly, other required change and the final classes:

public abstract class Buff<V> {
    public V value;
}
public interface Buffable<V extends Buff<?>> {
    public void buff(V buff);
}
// instead of primitive types, you should use their wrappers: double-->Double
public class DoubleBuff extends Buff<Double> {
    public double value;
}
public class DoubleBuffable implements Buffable<DoubleBuff> {
    public void buff(DoubleBuff buff) {
        //implementation
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Primitives can't be used as generic types. Try "Double" instead of "double".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.