java 接口 转换,Java中的转换(接口和类)

本文探讨了Java中的类型转换,特别是接口I、类A、B和C之间的关系。B类继承自A类,而C类继承自B类。A对象不能直接转换为B类型,因为这违反了Java的类型安全原则,即子类可以被当作父类类型使用,但父类不能被当作子类类型。理解这个原则有助于避免运行时ClassCastException。
摘要由CSDN通过智能技术生成

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:

aqVqA.jpg is a type of Programming_language, but Programming_language is not a type of

TRJcu.jpg

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值