我现在有一个项目,我犯了一个错误,我不知道为什么它会给我这个错误。
我的结构:
Class: Variable (commands.lib.Variable);
Class: ImageLoader extends Variable (commands.lib.Variable);然后,我将一个变量转换为一个ImageLoader:
// 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]);但这给了我一个错误:
Exception in thread "main" java.lang.ClassCastException: commands.lib.Variable cannot be cast to commands.variable.ImageLoader当然,我搜索了ClassCastException,这篇文章的结果是:Explanation of "ClassCastException" in Java
这里有人解释说:
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因此,对于我的代码,它将如下所示:
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所以我有点无知。我希望有人能帮助我,纠正错误。
大家好,
罗宾
发布于 2012-10-25 12:40:26
编辑:答案并没有真正回答这个问题,但没有删除,因为下面的评论有助于理解基本概念。
我一直对此感到困惑
但你看
这句话
Variable v = new ImageLoader();您正在将ImageLoader(Subclass)的一个对象存储到Variable(SuperClass),这很好
但这份声明
ImageLoader t = (ImageLoader)getVariable(ab[2]);您正在将Variable(superclass)转换为ImageLoader(SubClass),这在java中是不允许的,因此出现了错误。
发布于 2012-10-25 12:54:26
在java中,允许将超类转换为子类。我以前也做过。问题是ImageLoader不是制造出来的。我以为是在那里做的。
https://stackoverflow.com/questions/13068650
复制相似问题