【问题标题】:Java type mismatch when calling interface with it's own return type?使用自己的返回类型调用接口时Java类型不匹配?
【发布时间】:2016-03-20 21:11:45
【问题描述】:

过去几天我一直在努力解决这个问题,并搜索了我能想到的一切都无济于事。

我有一个类通过接口与另一个类交互。我遇到了一些类型不匹配错误,代码对我来说似乎很简单。

public class FooBar {
  Foo<? extends Bar> X = new Y();

  public void test(){
    if X.isA(X.B()){
       //do something; type mismatch here
    }

  }
}

界面:

public interface Foo<T extends Bar> {
  public T B();
  public boolean isA(T t);
}

实施:

public class Y implements Foo<T extends Bar> {
  public int B(){
    return 5;
  }

  public boolean isA(int num){
    int A = 10;
    return (A == num) ? true : false;

}

我的问题是 test() 方法。我通过接口获取一个数字,然后用相同的实现类实例对其进行测试,但这给了我一个捕获/类型不匹配错误。

CAP#1 从 ? 的捕获扩展 Bar扩展栏

CAP#2 从捕获的 ? 扩展 Bar扩展栏

我尝试了很多在搜索中找到的东西,但没有一个奏效。泛型和接口对我来说是新的,我还在学习它们。提前感谢您的帮助!

【问题讨论】:

  • 不应该 isA 使用 T 而不是 int 吗?或者类的签名改为public class Y implements Foo&lt;Integer&gt;
  • 作为旁注return (A == num) ? true : false; 可能只是return A == num;
  • Bar 类在哪里?
  • 您的X 是一个消费者,所以它应该是Foo&lt;? super Bar&gt;,如果甚至需要通配符的话。 stackoverflow.com/q/2723397/2891664
  • 一个不正确的项目是你有一个接口Foo&lt;T extends Bar&gt;。然后你有具体的类Y implements Foo&lt;T extends Bar&gt; 对于 Y,'T' 是 int 类型,这是无效的。 “T”不能是基元,必须是扩展 Bar 的类。

标签: java generics interface


【解决方案1】:

我已经更新了你的课程(为了清楚起见,我添加了缺少的 Bar 课程)。 您现在可以运行FooBar.main() 方法并获得您期望的结果:

public class FooBar {
    Foo x = new Y();

    public void test(){
        if(x.isA(x.B())){
            System.out.println("x.isA!");
        }
    }

    public static void main(String... args){
        FooBar fb = new FooBar();
        fb.test();
    }
}

public interface Foo<T extends Bar> {
    T B();
    boolean isA(T t);
}

public class Bar {}

public class ExtendsBar extends Bar {

    @Override
    public String toString(){
        return "Yes I extend Bar";
    }
}

public class Y implements Foo<ExtendsBar> {
    public ExtendsBar B() {
        return new ExtendsBar();
    }

    public boolean isA(ExtendsBar num) {
        return (num instanceof Bar);
    }
}

【讨论】:

    猜你喜欢
    • 2013-06-28
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    相关资源
    最近更新 更多