面向对象之多态---类型的转换与判断

对象的向上转型

格式: 父类名称 对象名 = new 子类名称();

Animal animal = new Cat();

创建了一只猫,当作动物来看待,没问题

含义: 右键创建一个子类对象,把它当作父类来看待使用

向上转型一定是安全的

类似于 double num = 100; / / 正确

// 抽象父类Animal
public  abstract  class Animal {
    public abstract void eat();
}

// 子类Cat重写eat方法
public class Cat extends Animal {

    @Override
    public void eat() {
        System.out.println("猫吃鱼");
    }
}

// 向上转型一定是安全的,没有问题的,正确的,但是也有一个弊端
// 对象一旦向上转型为父类,那么久无法调用子类原本特有的内容(子类特有方法)

// 解决方案: 用对象的向下转型【还原】
public class Main {
    public static void main(String[] args) {

        //对象的向上转型,就是,父类引用指向子类对象。
        Animal animal = new Cat();
        animal.eat();
    }
}

对象的向下转型

对象的向下转型,其实就是一个【还原】的动作

格式: 子类名称 对象名 = (子类名称) 父类对象;

含义:将父类对象,[还原]成为本来的子类对象

Animal animal = new Cat() // 本来是猫,向上转型成为动物

Cat cat = (Cat) anmial // 本来是猫,已经被当做动物了,还原成为本来的猫

Dog dog = (Dog) animal // 错误,因为对象创建的时候本来不是狗而是猫

注意事项:

1. 必须保证对象本来创建的时候,就是猫,才能向下转型成本来的猫

2. 如果对象创建的时候本来不是猫,现在非要向下转型成为猫,就会报错(java.lang.ClassCastException 类转化异常)

类似于: int num =(int) 10.0; // 可以 int num = (int) 10.5; //不可以,精度损失

// Ctrl + O 快速重写父类方法
// 这是Animal的另一个Dog子类
public class Dog  extends  Animal{
    @Override
    public void eat() {
        System.out.println("狗吃Shit");
    }
    public void watchHouse(){
        System.out.println("狗看家");
    }
}

用instanceof关键字来进行类型判断

/**
 * 如何才能知道一个父类引用的对象,本来是什么子类?
 *
 * 格式:
 *
 * 对象 instanseof 类名称
 *
 * 这将会得到一个boolean值结果,也就是判断前面的对象能不能当做后面类型的实例。
 */
public class Instanseof {
    public static void main(String[] args) {
        Animal animal = new Cat() ;//向上转型,本来是一只猫
        animal.eat(); // 猫吃鱼

        // 希望调用子类特有方法,需要向下转型
        // 判断一下父类引用animal本来是不是Dog
        if(animal instanceof Dog){
            Dog dog = (Dog) animal;
            dog.watchHouse();
        }
        if(animal instanceof Cat){
            Cat cat = (Cat) animal;
            cat.catchMouse();
        }
        System.out.println("=======");
        // 调用方法
        // 宠物猫方法
        giveMeAPetCat(new Cat());
        System.out.println("=======");
        // 宠物狗方法
        giveMeAPetDog(new Dog());
    }
    // 宠物猫
    public static void giveMeAPetCat(Animal animal){
        if(animal instanceof  Cat){
            Cat cat = (Cat) animal;
            cat.catchMouse();
        }
        if(animal instanceof  Dog){
            Dog dog = (Dog) animal;
            dog.watchHouse();
        }
    }
    // 宠物狗
    public static void giveMeAPetDog(Animal animal){
        if(animal instanceof Cat){
            Cat cat = (Cat) animal;
            cat.catchMouse();
        }
        if(animal instanceof Dog){
            Dog dog = (Dog) animal;
            dog.watchHouse();
        }
    }
}


猜你喜欢

转载自www.cnblogs.com/fenixG/p/12960682.html
今日推荐