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

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

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

  1. public abstract class Example<T, U> {
  2. public T t;
  3. public U u;
  4. public Example(T t, U u) {
  5. this.t = t;
  6. this.u = u;
  7. }
  8. abstract double distance(Example<T, U> other);
  9. }

特殊示例.java

  1. public class SpecialExample extends Example<Integer, Double> {
  2. public SpecialExample(Integer i, Double d) {
  3. super(i, d);
  4. }
  5. @Override
  6. double distance(Example<Integer, Double> other) {
  7. return (double)(t - other.t) + u * other.u;
  8. }
  9. }

badexample.java文件

  1. public class BadExample extends Example<String, String> {
  2. public BadExample(String s1, String s2) {
  3. super(s1, s2);
  4. }
  5. @Override
  6. double distance(Example<String, String> other) {
  7. return (double)(t.length() + other.t.length()) + (u.length() * other.u.length());
  8. }
  9. }

示例consumer.java

  1. public class ExampleConsumer<E extends Example> {
  2. private E example;
  3. public ExampleConsumer(E example) {
  4. this.example = example;
  5. }
  6. public double combine(E other) {
  7. return example.distance(other);
  8. }
  9. }

主.java

  1. class Main {
  2. public static void main(String[] args) {
  3. SpecialExample special = new SpecialExample(1, 2.0);
  4. ExampleConsumer<SpecialExample> consumer = new ExampleConsumer<>(special);
  5. BadExample bad = new BadExample("foo", "bar");
  6. consumer.combine(special); // compiles with warning
  7. // consumer.combine(bad); // doesn't compile = good!
  8. }
  9. }
ljo96ir5

ljo96ir51#

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

  1. public class ExampleConsumer<A, B, E extends Example<A, B>> {
  2. private E example;
  3. public ExampleConsumer(E example) {
  4. this.example = example;
  5. }
  6. public double combine(E other) {
  7. return example.distance(other);
  8. }
  9. }

主.java

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

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

展开查看全部

相关问题