向上转型(自动类型的提升)
多态的正常使用
向下转型(强制类型转换)
解决问题 父类引用不能使用子类中特有的成员
子类 对象 = (子类) 父引用
package PolymorphicInnerClass.demo2;
/**
* @author xiaowang
* @creat 2024/6/2 14:46
* @Description Java Lotus
*/
public class Test {
public static void main(String[] args) {
Father f=new Son();
System.out.println(f.num);
f.show();
// f.show2();检查父类中的成员方法
((Son)f).show2();
}
}
向下转型的注意事项
java.lang.ClassCastException
容易发生类型转换的异常
package PolymorphicInnerClass.demo3;
/**
* @author xiaowang
* @creat 2024/6/2 14:59
* @Description Java Lotus
*/
public abstract class Animal {
private String bread;
private String color;
public Animal(){
}
public Animal(String bread, String color) {
this.bread = bread;
this.color = color;
}
public String getBread() {
return bread;
}
public void setBread(String bread) {
this.bread = bread;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public abstract void eat();
}
package PolymorphicInnerClass.demo3;
/**
* @author xiaowang
* @creat 2024/6/2 15:00
* @Description Java Lotus
*/
public class Cat extends Animal{
public Cat() {
}
public Cat(String bread, String color) {
super(bread, color);
}
@Override
public void eat(){
System.out.println("猫吃鱼");
}
//子类特有方法
public void catchMouse(){
System.out.println("抓老鼠");
}
}
package PolymorphicInnerClass.demo3;
/**
* @author xiaowang
* @creat 2024/6/2 15:00
* @Description Java Lotus
*/
public class Dog extends Animal{
public Dog() {
}
public Dog(String bread, String color) {
super(bread, color);
}
@Override
public void eat() {
System.out.println("狗吃骨头");
}
public void lookDoor(){
System.out.println("狗看家");
}
}
package PolymorphicInnerClass.demo3;
/**
* @author xiaowang
* @creat 2024/6/2 15:00
* @Description Java Lotus
*/
public class Pig extends Animal{
public Pig() {
}
public Pig(String bread, String color) {
super(bread, color);
}
@Override
public void eat() {
System.out.println("猪拱白菜");
}
public void sleep(){
System.out.println("一直睡觉");
}
}
package PolymorphicInnerClass.demo3;
/**
* @author xiaowang
* @creat 2024/6/2 15:00
* @Description Java Lotus
*/
public class Test {
public static void main(String[] args) {
useAnimal(new Cat());
System.out.println("------------");
useAnimal(new Dog());
System.out.println("------------");
useAnimal(new Pig());
System.out.println("------------");
}
// public static void useAnimal(Cat c){
// c.eat();
// c.catchMouse();
// }
//
// public static void useAnimal(Dog d){
// d.eat();
// d.lookDoor();
// }
//
// public static void useAnimal(Pig p){
// p.eat();
// p.sleep();
// }
public static void useAnimal(Animal animal){
animal.eat();
if(animal instanceof Cat){
Cat cat=(Cat) animal;
cat.catchMouse();
}
if(animal instanceof Dog){
Dog dog=(Dog) animal;
dog.lookDoor();
}
if(animal instanceof Pig){
Pig pig=(Pig) animal;
pig.sleep();
}
}
}