类型强转、向上转型、向下转型

类型转换:
基本数据类型(boolean除外)之间可以互相转换。
引用类型转换的前提是存在继承或实现关系。
在强转之前,建议先使用instanceof 关键字判断。接口引用也可以利用instanceof关键字判断是否是子类的一个实例。
Integer 和 Long 之间没有继承和实现的关系,是兄弟关系,所以不能强转。
注意,包装类和基本类型也不可以强转。
Object 是所有类型的父类,所以可以强转为任意引用类型,但注意出现类型转换异常。
泛型不一定是什么类型,所以不可强转。

public class TestAnimal {
    public static void main(String[] args) {
        Animal animal = new Dog("大黄", "黄");
        //System.out.println(a.furColor); //不能通过编译
        System.out.println(animal instanceof Animal);//true
        System.out.println(animal instanceof Dog);//true
        Dog dog = (Dog)animal;
        Cat cat = (Cat)animal;//可以通过编译,但运行时出错
    }
}

class Animal {
    public String name;
    public Animal(String name) {
        this.name = name;
    }
}

class Dog extends Animal {
    public String furColor;
    public Dog (String name, String furColor) {
        super(name);
        this.furColor = furColor;
    }
}

class Cat extends Animal {
    private String furColor;
    public Cat (String name, String furColor) {
        super(name);
        this.furColor = furColor;
    }
}
View Code

 画图分析:

原文地址:https://www.cnblogs.com/Mike_Chang/p/7073135.html