Java:将类转换为不相关的接口 [英] Java: Casting a class to an unrelated interface

查看:101
本文介绍了Java:将类转换为不相关的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显然,这会导致编译错误,因为Chair与Cat无关:

Obviously, this results in a compilation error because Chair is not related to Cat:

class Chair {}
class Cat {}

class Test {
   public static void main(String[] args) {
       Chair chair = new Char(); Cat cat = new Cat();
       chair = (Chair)cat; //compile error
   }
}

只有在运行时,当我把一个Cat引用转换到不相关的接口Furniture,而编译器显然可以告诉Cat不实现家具时,会得到一个异常。

Why is it then, that I only get an exception at run time when I cast a Cat reference to the unrelated interface Furniture, while the compiler can obviously tell that Cat does not implement Furniture?

interface Furniture {}

class Test {
   public static void main(String[] args) {
       Furniture f; Cat cat = new Cat();
       f = (Furniture)cat; //runtime error
   }
}


推荐答案

编译的原因

interface Furniture {}

class Test {
   public static void main(String[] args) {
       Furniture f; Cat cat = new Cat();
       f = (Furniture)cat; //runtime error
   }
}

public class CatFurniture extends Cat implements Furniture {}

如果您创建一个 CatFurniture 实例,您可以将其分配给 Cat cat ,并且该实例可以转换为 Furniture 。换句话说,某些 Cat 子类型可能实现 Furniture 接口。

If you create a CatFurniture instance, you can assign it to Cat cat and that instance can be casted to Furniture. In other words, it's possible that some Cat subtype does implement the Furniture interface.

在你的第一个例子中

class Test {
    public static void main(String[] args) {
        Chair chair = new Char(); Cat cat = new Cat();
        chair = (Chair)cat; //compile error
    }
}

$ c> Cat sub >主席

it's impossible that some Cat subtype extends Chair unless Cat itself extends from Chair.

这篇关于Java:将类转换为不相关的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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