安全和不安全的向下传播示例?

时间:2014-06-03 14:25:23

标签: java casting

什么时候堕落不安全且安全?

安全(如此):source - [here]

class Useful {
  public void f() {}
  public void g() {}
}

class MoreUseful extends Useful {
  public void f() {}
  public void g() {}
  public void u() {}
  public void v() {}
  public void w() {}
}

public class RTTI {
  public static void main(String[] args) {
    Useful[] x = {
      new Useful(),
      new MoreUseful()
    };
    x[0].f();
    x[1].g();
    // Compile time: method not found in Useful:
    //! x[1].u();
    ((MoreUseful)x[1]).u(); // Downcast/RTTI
    ((MoreUseful)x[0]).u(); // Exception thrown
  }
} 

任何人都可以举例说明不安全的垮台吗?

1 个答案:

答案 0 :(得分:5)

任何时候堕落者都会丢失信息,这是不安全的。例如,

float pi = (float) Math.PI; // <-- unsafe cast double to float.
int i = (int) Long.MAX_VALUE; // <-- unsafe long to int
int min = (int) Long.MIN_VALUE; // <-- also unsafe long to int

也许你从OO的角度来看,

Long l = (Long) ((Object) "Hello"); // <-- unsafe String to Long casting.