Java规则 [英] Java rules for casting
问题描述
什么时候某个对象可以转换为另一个对象? casted对象必须是另一个对象的子类型吗?我想弄清楚规则...
编辑:我意识到我没有解释我的问题:基本上我将一个对象转换为接口类型。但是,在运行时,我得到一个 java.lang.ClassCastException
。我的对象需要发生什么,以便我可以把它转换到这个接口?它必须实现吗?
感谢
在Java中有两种类型的引用变量强制转换:如果您有一个引用
变量,引用了一个引用
-
子类型
对象,可以将其分配给子类型的
引用变量。
你必须做一个显式的转换来做
这个,结果是你可以
访问子类型的成员
这个新的引用变量。 -
向上转换:您可以显式或隐式地将引用
变量分配给超类型引用
变量。
这是一个本质上安全的操作
,因为赋值限制了新
变量的
访问功能。
是,您需要直接或间接实现 接口以启用将类对象引用分配给接口类型。 p> 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... 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 Thanks 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: 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屋!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?