[英]Java Downcasting/Upcasting
I am getting ClassCastEception in the following code. 我在以下代码中获得ClassCastEception。 Me class extends the person class.
我班延伸人班。 why can't i downcast the Me object to Person.
为什么我不能将Me对象丢给Person。 I can't understand the logic here.
我不明白这里的逻辑。 please anyone make me clear with good explanation.
请任何人给我清楚的解释。
public class Conv {
public class Person {
public void setName(String name) {
this.name = name;
}
public String name = "X";
public Person(String n) {
name = n;
}
/*
* many other variables and procedures
*/
}
public class Me extends Person {
/*
* nothing more in this class
*/
public Me(String n) {
super(n);
}
}
public void test() {
Person p = new Person("Roy");
Me a = (Me) p;
System.out.println(a.name);
}
public static void main(String[] args) {
new Conv().test();
}
}
Every Cat is an Animal. 每只猫都是动物。 But not every Animal is a Cat.
但是,并非每个动物都是猫。 Same rule applies here.
同样的规则在这里适用。 You cannot turn every
Person
to Me
. 你不能把每个
Person
转向Me
。 Where as every Me
is a Person
. 每个
Me
都是一个Person
。
You are creating p
as new Person
, not new Me
. 您正在将
p
创建为new Person
,而不是new Me
。 For casting, it's the runtime type that is checked. 对于转换,将检查运行时类型。 If you create
Person p = new Me("Roy")
, then you can cast it to Me
because in reality (during runtime) even though it's declared as Person
, it is a Me
. 如果创建
Person p = new Me("Roy")
,则可以将其Me
为Me
因为实际上(在运行时),即使它被声明为Person
,它也是Me
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.