devxlogo

Dynamic class casting

Dynamic class casting

Question:
Does java have dynamic_cast? If so, how is itused?

Answer:
All class casts of nonprimitive types in Java are dynamic and performed at runtime.In C++ the dynamic_cast operator will producea null pointer if a type conversion cannot be performed. In Java, the cast operation will throw a ClassCastException. Where in C++ you wouldcompare the result of a cast operation to nullto determine success, in Java you would catcha ClassCastException. For example:

// C++if(String *a = dynamic_cast(b)) {// success} else {// failure}// Javatry {    String a = (String)b;    // success} catch(ClassCastException e) {    // failure}

devx-admin

Share the Post: