ClassCastException:类型转换异常

ClassCastException:类型转换异常

一般在多态的向下转型中容易出现

代码演示

class Animal {
	public void eat(){}
}

class Dog extends Animal {
	public void eat() {}
	
	public void lookDoor() {
	
	}
}

class Cat extends Animal {
	public void eat() {
	
	}
	
	public void playGame() {
		
	}
}

public class DuoTaiDemo5 {
	public static void main(String[] args) {
		//内存中的是狗
		Animal a = new Dog();
		Dog d = (Dog)a;
		
		//内存中是猫
		a = new Cat();
		Cat c = (Cat)a;
		
		//内存中是猫
		Dog dd = (Dog)a; //ClassCastException
	}

结果:

java.lang.ClassCastException: com.tellhow.test.jwh.bzword.Cat cannot be cast to com.tellhow.test.jwh.bzword.Dog
发布了186 篇原创文章 · 获赞 0 · 访问量 4122

猜你喜欢

转载自blog.csdn.net/qq_40332952/article/details/104717019
今日推荐