Jiaoche jiaoche = new Jiaoche();
feiji plane = new feiji();
Jiaotonggongju jiaotonggongju = jiaoche;
if(jiaotonggongju instanceof feiji) {
feiji plane2 = (feiji) jiaotonggongju;
}else {
System.out.println("123");
}
if(jiaotonggongju instanceof Jiaoche) {
Jiaoche jiaoche2 = (Jiaoche)jiaotonggongju;}
else {System.out.println("321");}
这样子只能转换Jiaoche,feiji就转换不了了,当我两种都转换的时候就报错了
instanceof只是判断一个对象是否某个类或者子类的对象或者实例,换句话说instanceof只是用来规避有风险或出错的强制转换,而不是转换的本身。对象之间能否转换而风险或出错取决于对象之间的相互关系。