Java中的转换(接口和类) [英] Casting in Java(interface and class)

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

问题描述

if:

 接口I {} 

类A实现I {}

class B extends A {}

class C extends B {}

A a = new A();
B b = new B();

为什么a =(B)(I)b;是正确的
,但b =(B)(I)a;是假的?

我发现转换是很混乱,什么是最好的方式来了解, up cast一个对象?

解决方案

与代码示例中回答问题相关的唯一事情如下:

  B类扩展A {} 

这意味着B是A的子类。子类可以转换为超类类型,但是超类不能转换为子类类型。


$ b 因此,A不能转换为类型B.



以这种方式思考逻辑:



Programming_language 的类型,但 Programming_language 不是


if:

interface I{}

class A implements I{}

class B extends A{}

class C extends B{}

A a = new A();
B b = new B();

Why a = (B)(I)b; is correct
but b = (B)(I)a; is false?

I find casting to be very confusing, what is the best way to understand if I can down cast or up cast an object?

解决方案

The only thing of relevance to answering the question in your coding sample is the following:

class B extends A{}

This means that B is a subclass of A. Subclasses can be cast to super class types, but super class cannot be cast to subclass types.

Therefore, A cannot be cast to type B.

Why? Think about the logic this way:

is a type of Programming_language, but Programming_language is not a type of

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

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