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?
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
}
}
Primitives can't be used as generic types. Try "Double" instead of "double".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With