barsdeveloper
barsdeveloper

Reputation: 960

JAVA: Type parameter hiding class type

I have this

abstract class Operand {
    public abstract <T extends Operand> Operand operation(Operator operator, T operand);
}
abstract class Numeric extends Operand {
}
class Integer extends Numeric 
    @Override
    public <Integer> Operand operation(Operator operator, Integer operand) {//problem
    }
}

How can I solve this situation? I don't want to use generics in the class Operand (so I have Operand) because I need Operand to be a single type. Inside the Integer's method I need to call the constructor (new Integer(arg)), a solution could be to call that method in some other way. Solutions?

Upvotes: 0

Views: 269

Answers (3)

Braj
Braj

Reputation: 46861

Try with overloaded method

abstract class Operand {
    public abstract <T extends Operand> Operand operation(Operator operator, T operand);
}

abstract class Numeric<T extends Numeric<T>> extends Operand {
    public abstract Operand operation(Operator operator, T operand);
}

class Integer extends Numeric<Integer> {

    @Override
    public Operand operation(Operator operator, Integer operand) {
        // add your Integer specific code here
        return null; // replace null with actual returned value
    }

    @Override
    public <T extends Operand> Operand operation(Operator operator, T operand) {
        // simply call to overridden Integer specific method
        // no harm to downcast it here
        return operation(operator, (Integer) operand); 
    }

}

Upvotes: 2

newacct
newacct

Reputation: 122489

It seems to me you want something like this:

abstract class Operand<T, U> {
    public abstract T operation(Operator operator, U operand);
}
abstract class Numeric<T, U> extends Operand<T, U> {
}
class Integer extends Numeric<Integer, Integer>
    @Override
    public Integer operation(Operator operator, Integer operand) {
    }
}

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201467

The issue is your method declaration in Operand, which is <T extends Operand>, you must match that "contract" with your implementation -

class Integer extends Numeric {
  @Override
  public <T extends Operand> Operand operation(Operator operator, T operand) {
    // Like this....
  }
}

Upvotes: 1

Related Questions