用于转换的 Java 规则 [英] Java rules for casting

查看:32
本文介绍了用于转换的 Java 规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么时候可以将某个对象转换为另一个对象?铸造对象是否必须是另一个对象的子类型?我想弄清楚规则...

When can a certain object be cast into another object? Does the casted object have to be a subtype of the other object? I'm trying to figure out the rules...

编辑:我意识到我根本没有解释我的问题:基本上我将对象转换为接口类型.但是,在运行时,我得到一个 java.lang.ClassCastException.我的对象需要做什么才能将它转换到这个接口?它必须执行吗?

Edit: I realized that I didn't explain my issue at all: basically I am casting an object to an interface type. However, at run-time, I get a java.lang.ClassCastException. What needs to happen with my object so that I can cast it to this interface? Does it have to implement it?

谢谢

推荐答案

在 Java 中有两种类型的引用变量转换:

In Java there are two types of reference variable casting:

  • 低头:如果您有参考资料引用子类型的变量对象,您可以将其分配给子类型的引用变量.你必须做一个明确的演员这个,结果是你可以访问子类型的成员这个新的参考变量.

  • Downcasting: If you have a reference variable that refers to a subtype object, you can assign it to a reference variable of the subtype. You must make an explicit cast to do this, and the result is that you can access the subtype's members with this new reference variable.

Upcasting:您可以分配参考超类型引用的变量显式或隐式变量.这是一个本质安全的操作因为赋值限制了新的访问能力变量.

Upcasting: You can assign a reference variable to a supertype reference variable explicitly or implicitly. This is an inherently safe operation because the assignment restricts the access capabilities of the new variable.

,您需要直接或间接实现接口,以便将您的类对象引用分配给接口类型.

Yes, you need to implement the interface directly or indirectly to enable assigning your class object reference to the interface type.

这篇关于用于转换的 Java 规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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