【问题标题】:JAVA: Type parameter hiding class typeJAVA:类型参数隐藏类类型
【发布时间】:2014-06-27 14:54:59
【问题描述】:

我有这个

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
    }
}

我该如何解决这种情况? 我不想在 Operand 类中使用泛型(所以我有 Operand),因为我需要 Operand 是单一类型。在 Integer 的方法中,我需要调用构造函数 (new Integer(arg)),解决方案可能是以其他方式调用该方法。 解决方案?

【问题讨论】:

    标签: java generics inheritance types covariance


    【解决方案1】:

    尝试使用重载方法

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

    【讨论】:

      【解决方案2】:

      问题是您在Operand 中的方法声明,即&lt;T extends Operand&gt;,您必须将该“合同”与您的实现相匹配 -

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

      【讨论】:

      • 但是Integer.operation的第二个参数总是Integer,不能是其他类型。
      • @biowep 然后你应该使 Numeric 和 Operand 类通用,因为你有一个抽象的通用方法。你必须实现它。
      【解决方案3】:

      在我看来你想要这样的东西:

      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) {
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多