java.lang.ClassCastException 强制类型转化异常

java.lang.ClassCastException 强制类型转换异常

主要原因 : 当父类强制转换成子类时候出现的异常  ,除非是子类转换成父类,父类再转换给子类

public class Test {
	public static void main(String[] args) {
		Parent parent = new Child();
		Child child = (Child) parent;
		child.getAge();
		child.getName();
	}
}
class Parent{
	public void getName(){
		System.out.println("hello world");
	}
}
class Child extends Parent{
	public void getAge(){
		System.out.println("25");
	}
}
 

如果把代码稍微修改下,就会报ClassCastException

public class Test {
	public static void main(String[] args) {
		Parent parent = new Parent();
		Child child = (Child) parent;
		child.getAge();
		child.getName();
	}
}
class Parent{
	public void getName(){
		System.out.println("hello world");
	}
}
class Child extends Parent{
	public void getAge(){
		System.out.println("25");
	}
}
 

猜你喜欢

转载自meteor-1988.iteye.com/blog/1738551