在下面的程序中的哪里放置try catch来处理Class Cast Exception?
Class Animal { }
Class Dog extends Animal { }
Class Cat extends Animal { }
Class MainRunner {
public static void main(String args[]) {
System.out.println("Main method started");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the key value");
int key = sc.nextInt();
Animal a = null;
switch (key) {
case 1 : a = new Cat(); break;
case 2 : a = new Dog(); break;
default : System.out.println("invalid choice");
return;
}
Dog d = (Dog)a;
System.out.println("main method ended");
}
}
Cat类未进行向下转换,因此当输入键值1时,它将抛出Class cast Exception。如何使用try catch处理它?在哪里插入try catch,以便对其进行处理?
最佳答案
是@Pshemo提到的;您应该使用instanceof运算符检查其Dog实例是否存在,并相应地对其进行初始化
Dog d=null;
if(a instanceof Dog)
d=(Dog)a;
System.out.println(d);
理想情况下,您无需向下转换。除非您必须调用由子类实现的专用方法。否则,应使用接口/父类方法。
example : a.eat() // eat will be present in animal and will be implemented differently in each sub-class dog and cat.
但是如果您需要树皮,例如;那么您可能需要转播,但要使用instanceof以安全的方式进行转播
if (a instanceof Dog) ((Dog)a).bark();
else syso("Animal cannot bark");