[英]Downcasting objects in Java
class A{
}
public class Demo
{
public static void main(String s[])
{
Object o=(Object) new Demo();
if (((A)(o)) instanceof Object)
{
System.out.println("true");
}
}
}
运行类Demo.java时出现异常:
java.lang.ClassCastException: Demo cannot be cast to A
如何垂头丧气o
参考class A
?
仅当Demo
扩展了A
,您才能这样做,否则,您无法将类对象转换为任何其他类型。
public class Demo extends A {
让我们从头开始:这是糟糕的代码。 话虽如此:
一些注意事项:
垂头丧气的例子:
public class A {
int variable = 0;
}
public class Demo extends A{
}
public void testDowncast(){
Demo myClass = new Demo();
myClass.variable = 2;
A morphingTime = myClass;
System.out.println("And now Power Ranger Demo has turned into Mighty A:");
System.out.println("I am: "+morphingTime.getClass() + " and my variable is: " + morphingTime.variable);
}
RJ的答案是正确的
仅当
Demo
扩展A
,您才能这样做
供您参考,分配给Object
时无需键入强制转换任何Object
Object o= new Demo();
并且每个对象将始终是Object的instanceof
即您对类对象的条件instanceof Object
始终为true
为什么要尝试以这种方式做事情((A)(o))
而不用instanceof
来检查类型,而应该这样做,
if (o instanceof A)
首先,您将获得“ ClassCastException”,因为您的实际对象“ o”属于类“ Demo”,而类“ Demo”和“ A”不在同一继承树中。 您不会因为仅将对象强制转换为类“ Object”而获得编译错误(因为“ A”和“ Object”在同一继承树中)。 要解决您的情况,您应该更改代码,使它们(“ Demo”和“ A”)都成为同一继承树的一部分。 例如,您可以从A扩展Demo。然后,检查对象'o',而不进行这样的强制转换
if (o instanceof A) {
// now cast to 'A'
// and invoke any accessible method (or etc.) that class A provides
((A)o).doSomthingMathod();
}
首先,您无需将Demo实例强制转换为对象,因为无需强制转换即可将Demo引用分配给Object类,因为Object是所有java类的超类。
public class Demo extends com.A {
}
您只需将代码重写为
Object o=new Demo();
if (o instanceof A)
{
System.out.println("true");
}
然后查看Demo extends A
变化
向下转换是将基类的引用转换为其派生类之一的行为。
例如 :
public class Parent{}
public class Child extends Parent{}
public static void main(String args[]){
Parent parent = new Child(); // Parent is parent class of Child, parent variable holding value of type Child
Child child = (Child)parent; // This is possible since parent object is currently holding value of Child class
}
您可以参考此问题以获得答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.