明显的类型冲突,但可以编译 [英] Apparent type violation, but compiles

查看:59
本文介绍了明显的类型冲突,但可以编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下代码段会编译? OtherInterface 不会扩展 Concrete ,所以我敢打赌这不会编译的肾脏.但确实如此.

Why does the below snippet compile ? OtherInterface does not extends Concrete so I would have bet a kidney that this wouldn't compile. But it does.

public class Test {

    public static interface SomeInterface {}

    public static interface OtherInterface{}

    public static class Concrete implements SomeInterface {

       public <T extends Concrete> T getConcrete() {
            return null;
       }
    }

    public static void doStuff() {
        Concrete c = new Concrete();
        OtherInterface iCompile = c.getConcrete();
    }
}

另一方面,下一个代码段不编译,这是我所期望的.

On the other hand, the next snippet does not compile, which is what I expect.

public class Test {

    public static interface SomeInterface {}

    public static class UnrelatedClass{}

    public static class Concrete implements SomeInterface {

       public <T extends Concrete> T getConcrete() {
            return null;
       }
    }

    public static void doStuff() {
        Concrete c = new Concrete();
        UnrelatedClass iCompile = c.getConcrete();
    }
}

推荐答案

区别在这里:

public static interface OtherInterface{} ...
OtherInterface iCompile = c.getConcrete();

vs.

public static class UnrelatedClass{} ...
UnrelatedClass iCompile = c.getConcrete();

含义:在第一种情况下,您调用该方法以返回某个接口的实例.接口可以是 any 类.

Meaning: in the first case, you call the method to return an instance of some interface. Interfaces can be any class.

在第二个示例中,您 instruction 返回的类型是 specific 类!已知的类,不会实现该其他接口!

In the second example, you instruct that returned type is of be a specific class! A class which is known, and that does not implement that other interface!

错误消息:

原因:对于类型变量T,不存在上限为UnrelatedClass,Concrete的唯一最大实例

reason: no unique maximal instance exists for type variable T with upper bounds UnrelatedClass,Concrete

在这里非常具体.

换句话说:编译器在该赋值的左侧进行分解-确定有效类型.并且 UnrelatedClass 不能永远成为 Concrete -因为类 UnrelatedClass 不会扩展具体

In other words: the compiler factors in the left hand side of that assignment - to determine the valid types. And UnrelatedClass can never be a Concrete - because the class UnrelatedClass does not extend Concrete!

SomeInterface 之类的东西也可以 实现 OtherInterface .

Whereas something that is SomeInterface can as well implement OtherInterface.

这篇关于明显的类型冲突,但可以编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆