Search code examples
javagenericsinheritancetypescovariance

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?


Solution

  • 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); 
        }
    
    }