Java:将类转换为不相关的接口

编程入门 行业动态 更新时间:2024-10-26 04:28:45
本文介绍了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:将类转换为不相关的接口

本文发布于:2023-07-30 14:11:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1250157.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   不相关   接口   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!