首先是可以的。前提是:此父类对象为子类对象强转的结果 例如:
Father father = (Father)son;
当这种情况时,可以用instanceof判断是否是子类类型(实际) 然后强转回去
if(father instanceof Son)
Son son =(Son)father;
除此之外,不行。
往深了讲。子类强制转换为父类对象时,并没有实际丢失它原有内存空间(比父类多的那些部分)只是暂时不可访问。所以能再转回来。
另:父类对象可接受任何子类对象–此时发生自动转型–》转为父类类型–》所以能够再转回来。用instanceof 是防止错误的一种方式。
所以我们可以有用object来接收任意类型的对象,然后再转换为它实际应该是的对象即可。
(地址一致还是指向那个位置,只是子类对象转为父类对象后,子类对象额外的信息就无法访问了。再转回来就可以访问了。)
public static void main(String[] args) {
Father father = new Father();
Father father2 = new Father();
father.setAge(3);
father.setName("333");
father2.setAge(4);
father2.setName("444");
Son son = new Son();
Son son2 = new Son();
son.setAge(1);
son.setHouse("11");
son.setName("111");
son2.setAge(2);
son2.setHouse("22");
son2.setName("333");
//可以将转换后的子类对象,再转换回来
Father father3 = son;
boolean result =(father3 instanceof Son) ;
//true
System.out.println("father3 instanceof Son:" +result);
System.out.println(father3);
Son son3 = (Son) father3;
System.out.println(son3);
//无法将原本的父类对象转换为子类对象
//Exception in thread "main" java.lang.ClassCastException: com.hgh.extendstest.Father cannot be cast to com.hgh.extendstest.Son at com.hgh.extendstest.Test.main(Test.java:30)
son=(Son) father;
System.out.println(son);
}