首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java: ClassCastException

Java: ClassCastException
EN

Stack Overflow用户
提问于 2012-10-25 12:31:21
回答 2查看 226关注 0票数 2

我现在有一个项目,我犯了一个错误,我不知道为什么它会给我这个错误。

我的结构:

代码语言:javascript
复制
Class: Variable (commands.lib.Variable);
Class: ImageLoader extends Variable (commands.lib.Variable);

然后,我将一个变量转换为一个ImageLoader:

代码语言:javascript
复制
// There is a variable made with: Variable v = new ImageLoader();
public static Variable(commands.lib.Variable) getVariable(String value){...}
ImageLoader t = (ImageLoader)getVariable(ab[2]);

但这给了我一个错误:

代码语言:javascript
复制
Exception in thread "main" java.lang.ClassCastException: commands.lib.Variable cannot be cast to commands.variable.ImageLoader

当然,我搜索了ClassCastException,这篇文章的结果是:Explanation of "ClassCastException" in Java

这里有人解释说:

代码语言:javascript
复制
Animal a = new Dog();
Dog d = (Dog) a; // no problem, the type animal can be casted to a dog, because its a dog
Cat c = (Dog) a; // raises class cast exception, you cant cast a dog to a cat

因此,对于我的代码,它将如下所示:

代码语言:javascript
复制
Variable a = new ImageLoader();
ImageLoader b = (ImageLoader) a; // This should work, but will throw a ClassCastException
Array c = (Array) a; // This should throw a error

所以我有点无知。我希望有人能帮助我,纠正错误。

大家好,

罗宾

EN

回答 2

Stack Overflow用户

发布于 2012-10-25 12:40:26

编辑:答案并没有真正回答这个问题,但没有删除,因为下面的评论有助于理解基本概念。

我一直对此感到困惑

但你看

这句话

代码语言:javascript
复制
Variable v = new ImageLoader();

您正在将ImageLoader(Subclass)的一个对象存储到Variable(SuperClass),这很好

但这份声明

代码语言:javascript
复制
ImageLoader t = (ImageLoader)getVariable(ab[2]);

您正在将Variable(superclass)转换为ImageLoader(SubClass),这在java中是不允许的,因此出现了错误。

票数 0
EN

Stack Overflow用户

发布于 2012-10-25 12:54:26

在java中,允许将超类转换为子类。我以前也做过。问题是ImageLoader不是制造出来的。我以为是在那里做的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13068650

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档