## 强制类型转换 Java 中所有的强转,都依赖于等于或者put赋值时,右边实际指向的类型 与 强转类型之间的继承关系,如果强转的类型间没有父子关系(null 是一切人的兄弟),就会出 ClassCastException ```java Object i= null; System.out.println((Integer) i); Object i= "string"; System.out.println((Integer) i); ``` 上面的不会抛空指针,只输出一个 null 下面的会抛 `java.lang.ClassCastException` ### 那么基础类型的父子关系是啥? ```mermaid graph BT A[byte] --> B[short] B --> C[int] C --> D[long] D --> E[float] E --> F[double] G[char] --> C G --> D G --> E G --> F H[boolean] --> I[不参与数值转换] style A fill:#f9f,stroke:#333,stroke-width:2px style B fill:#fcc,stroke:#333,stroke-width:2px style C fill:#cfc,stroke:#333,stroke-width:2px style D fill:#ccf,stroke:#333,stroke-width:2px style E fill:#fcf,stroke:#333,stroke-width:2px style F fill:#cff,stroke:#333,stroke-width:2px style G fill:#ffc,stroke:#333,stroke-width:2px style H fill:#f99,stroke:#333,stroke-width:2px style I fill:#ddd,stroke:#333,stroke-width:2px ```