抽象继承中未检查的泛型(java)

c9qzyr3d  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(343)

我收到一条编译警告:“exampleconsumer.java使用未检查或不安全的操作。” return example.distance(other); . 如何正确检查类型?显然,我需要强制执行这些类型是相同的。
这是我的密码:
示例.java

public abstract class Example<T, U> {
  public T t;
  public U u;

  public Example(T t, U u) {
    this.t = t;
    this.u = u;
  }

  abstract double distance(Example<T, U> other);
}

特殊示例.java

public class SpecialExample extends Example<Integer, Double> {
  public SpecialExample(Integer i, Double d) {
    super(i, d);
  }

  @Override
  double distance(Example<Integer, Double> other) {
    return (double)(t - other.t) + u * other.u;
  }
}

badexample.java文件

public class BadExample extends Example<String, String> {
  public BadExample(String s1, String s2) {
    super(s1, s2);
  }

  @Override
  double distance(Example<String, String> other) {
    return (double)(t.length() + other.t.length()) + (u.length() * other.u.length());
  }
}

示例consumer.java

public class ExampleConsumer<E extends Example> {
  private E example;

  public ExampleConsumer(E example) {
    this.example = example;
  }

  public double combine(E other) {
    return example.distance(other);
  }
}

主.java

class Main {
  public static void main(String[] args) {
    SpecialExample special = new SpecialExample(1, 2.0);

    ExampleConsumer<SpecialExample> consumer = new ExampleConsumer<>(special);

    BadExample bad = new BadExample("foo", "bar");

    consumer.combine(special); // compiles with warning
   // consumer.combine(bad); // doesn't compile = good!
  }
}
ljo96ir5

ljo96ir51#

这里有一个解决方案:
示例consumer.java

public class ExampleConsumer<A, B, E extends Example<A, B>> {
  private E example;

  public ExampleConsumer(E example) {
    this.example = example;
  }

  public double combine(E other) {
    return example.distance(other);
  }
}

主.java

class Main {
  public static void main(String[] args) {
    // ...
    ExampleConsumer<Integer, Double, SpecialExample> consumer = new ExampleConsumer<>(special);
    // ...
  }
}

但我不想重复main.java中的double/integer类型:/

相关问题