小时候的动态打字 class
Dynamic typcasting as a child class
我有一个父 class Parent
,三个 class 扩展它:ChildOne
、ChildTwo
和 ChildThree
,每个其中覆盖了 Parent
class 中的方法。我创建了一个 Parent
对象数组,然后动态地(根据用户输入)创建了其中一个子 class 对象的对象。在此之后,我需要遍历 Parent[]
数组并希望将每个元素打字到它的 "real" class (子 classes 之一)以便使用适当的覆盖方法。
我尝试为子 class 类型创建一个变量,如下所示:
for (int i = 0; i < parents.length; i++) {
try {
Parent par = new Parent();
par = parents[i];
switch (par.getType()) {
case "one":
ChildOne child1 = (ChildOne)par;
System.out.println(child1.overridenMethod());
break;
case "two":
ChildTwo child2 = (ChildTwo)par;
System.out.println(child2.overridenMethod());
break;
case "three":
ChildThree child3 = (ChildThree)par;
System.out.println(child3.overridenMethod());
break;
}
} catch (NullPointerException npe) {
System.out.println("No child at position: " + i);
}
}
但是我收到一条错误消息说 ChildThree
不能转换为 ChildTwo
。似乎在第一个成功类型转换的元素之后,par
对象仍然是被类型转换为 class 的任何子对象的子对象 class。
我该如何解决这个问题,并能够根据数组中每个对象的 class 进行类型转换?
非常感谢!
覆盖意味着您在父类中有一个方法,而子类正在覆盖其功能。
您可以在您的案例中直接使用多态性。无需铸造:
for (Parent par: parents) {
try {
System.out.println(par.overridenMethod());
} catch (NullPointerException npe) {
System.out.println("No child at position: " + i);
}
}
如前所述,不需要转换,因为您在每个对象上调用的方法已经在 class Parent 中定义。所以你可以简单地写:
for (int i = 0; i < parents.length; i++) {
Parent par = parents[i];
System.out.println(par.overridenMethod());
}
关于您的类型转换错误,我的猜测是您的 getType 方法有误。它可能 returns 是您的一个 Child 实现的错误值,您最终会进入错误的 case 块。通常你应该在转换对象时使用 instanceof:
if(par instanceof ChildOne){
ChildOne child1 = (ChildOne)par;
}
我有一个父 class Parent
,三个 class 扩展它:ChildOne
、ChildTwo
和 ChildThree
,每个其中覆盖了 Parent
class 中的方法。我创建了一个 Parent
对象数组,然后动态地(根据用户输入)创建了其中一个子 class 对象的对象。在此之后,我需要遍历 Parent[]
数组并希望将每个元素打字到它的 "real" class (子 classes 之一)以便使用适当的覆盖方法。
我尝试为子 class 类型创建一个变量,如下所示:
for (int i = 0; i < parents.length; i++) {
try {
Parent par = new Parent();
par = parents[i];
switch (par.getType()) {
case "one":
ChildOne child1 = (ChildOne)par;
System.out.println(child1.overridenMethod());
break;
case "two":
ChildTwo child2 = (ChildTwo)par;
System.out.println(child2.overridenMethod());
break;
case "three":
ChildThree child3 = (ChildThree)par;
System.out.println(child3.overridenMethod());
break;
}
} catch (NullPointerException npe) {
System.out.println("No child at position: " + i);
}
}
但是我收到一条错误消息说 ChildThree
不能转换为 ChildTwo
。似乎在第一个成功类型转换的元素之后,par
对象仍然是被类型转换为 class 的任何子对象的子对象 class。
我该如何解决这个问题,并能够根据数组中每个对象的 class 进行类型转换?
非常感谢!
覆盖意味着您在父类中有一个方法,而子类正在覆盖其功能。
您可以在您的案例中直接使用多态性。无需铸造:
for (Parent par: parents) {
try {
System.out.println(par.overridenMethod());
} catch (NullPointerException npe) {
System.out.println("No child at position: " + i);
}
}
如前所述,不需要转换,因为您在每个对象上调用的方法已经在 class Parent 中定义。所以你可以简单地写:
for (int i = 0; i < parents.length; i++) {
Parent par = parents[i];
System.out.println(par.overridenMethod());
}
关于您的类型转换错误,我的猜测是您的 getType 方法有误。它可能 returns 是您的一个 Child 实现的错误值,您最终会进入错误的 case 块。通常你应该在转换对象时使用 instanceof:
if(par instanceof ChildOne){
ChildOne child1 = (ChildOne)par;
}