public class Primitive {
public static void main(String []args) {
byte x=5;
Double y=(Double)x; //Error : Cannot cast from byte to Double.
Byte n=7;
Double m=(Double)n; //Error : cannot cast from Byte to Double.
double c=n; //working right ..."double is primitive and Byte is object ".
}
}
Run Code Online (Sandbox Code Playgroud)
防止将Byte转换为Double的重点是什么?..如果我没有错,我知道Double to Byte的精确原因.
为什么不能将原始值(例如,double)强制转换为Object(例如,Byte)?
double x = 99;
Byte r = (Byte) x; // Error: Cannot cast from double to Byte
System.out.println(r);
Run Code Online (Sandbox Code Playgroud)