Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java class implementing a method with a parameter that is of the subtype specified in the interface

Tags:

java

generics

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?

like image 414
user2501337 Avatar asked Nov 21 '25 10:11

user2501337


2 Answers

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
    }
}
like image 51
acdcjunior Avatar answered Nov 22 '25 23:11

acdcjunior


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

like image 37
ssindelar Avatar answered Nov 23 '25 00:11

ssindelar