首页 > 解决方案 > 泛型返回类型方法中的不兼容类型 (Java)

问题描述

从 C++ 到 Java 的新手。具有通用返回类型的方法将无法编译。我认为这是因为我没有指定泛型方法的类型,但我什至不知道该怎么做。下面的代码不编译说:error: incompatible types: AnInterface cannot be converted to I ... where I is a type-variable:

在我看来,类型I肯定看起来与返回类型兼容,get因为我明确声明I要扩展AnInterface

import java.util.*;

interface AnInterface {
  public int aMethod();
}

class AClass implements AnInterface {
  AClass() { l = new ArrayList<>(); }

  public int aMethod() { return 1; }
  public void add(AnInterface x) { l.add(x); }
  public AnInterface get() { return l.get(0); }

  // method on() will not compile
  public <I extends AnInterface> I on(int x) { I i = get(); return i; }

  List<AnInterface> l;
}

class BClass implements AnInterface {
  public int aMethod() { return 2; }
}

class Main
{
  public static void main(String[] args)
  {
    AClass a = new AClass(); 
    BClass b = new BClass();
    a.add(b);
    // How do I even call AClass::on()
    // BClass x = a.on<BClass>(); // I expect to call on() like this
  }
}

标签: javagenerics

解决方案


仔细看看方法on

public <I extends AnInterface> I on() {
    I i = get(); 
    return i; 
}

I = BClass用手段调用它get()必须返回一个BClass. get但是is的签名public AnInterface get(),意味着我们只知道它返回一个AnInterface实现。它可以是BClass,但也可以是其他任何实现AnInterface

你可以on这样改变:

public AnInterface I on() {
    AnInterface i = get();
    return i;
}

签名现在显示on返回的东西正在实现AnInterface,这与我们从中返回的类型一致get

实际上,您的示例已经清楚地说明了为什么您发布的代码无法进行类型检查。

AClass a = new AClass(); 
AClass b = new AClass();
a.add(b);
BClass c = a.<BClass>on();

我们希望调用on返回实例b,因为这是添加到的第一个元素a。但是b是类型AClass,不是BClass。如果编译器不拒绝该程序,我们将在typeAClass的变量中有一个 的实例。cBClass


推荐阅读