【问题标题】:Unchecked generic in abstract inheritance (java)抽象继承中未选中的泛型(java)
【发布时间】:2019-06-27 20:03:56
【问题描述】:

我收到一个编译警告:“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!
  }
}

【问题讨论】:

    标签: java generics inheritance abstract-class


    【解决方案1】:

    这里有一个解决方案:

    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 类型:/

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 2011-04-11
      • 2010-10-13
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多