A Java class that implements a method with parameters that are subtypes specified in the interface
I had some trouble mastering generic drugs I've read Oracle's tutorial on generics, which doesn't seem to solve my problem I don't know what to search for when I find the answer
Suppose 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 a class that inherits buff and has a member "value", but specify the type of value (see doublebuff) I also want to define the class that implements the buff method using the input parameter, which belongs to the subtype of buff
Doublebuffable is a class that implements bufferable, but you need to enter doublebuff instead of stringbuff
Did I correctly express my generic?
Solution
The first is grammar Statement:
public interface Buffable<V> {
public void buff(Buff<V extends Buff> buff);
}
should:
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 said:
In this way, the following statement will better suit your statement:
public interface Buffable<V extends Buff<?>> {
public void buff(V buff);
}
You may want to change Part if you need a more specific buff type
Finally, other required changes and 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
}
}
