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

时间:2019-02-04 04:18:39

标签: java generics inheritance abstract-class

我收到编译警告:“ ExampleConsumer.java使用未经检查或不安全的操作。”在return example.distance(other);行上。如何正确检查类型?显然我需要强制类型相同。

这是我的代码:

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

SpecialExample.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());
  }
}

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

Main.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!
  }
}

1 个答案:

答案 0 :(得分:0)

这是一种解决方案:

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

Main.java

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

但是我不想在Main.java中重复Double / Integer类型:/