type casting

  • Type casting means treating a variable of one type as though it is another type.
  • upcast = implicit, downcast = explicit
  • When up casting primitives as shown below from left to right, automatic conversion occurs. But if you go from right to left, down casting or explicit casting is required. byte 􀃆 short 􀃆 int 􀃆 long 􀃆 float 􀃆 double
  • When it comes to object references you can always cast from a subclass to a superclass because a subclass object is also a superclass object. You can cast an object implicitly to a super class type (i.e. upcasting). If this were not the case polymorphism wouldn’t be possible.
  • You can cast down the hierarchy as well but you must explicitly write the cast and the object must be a legitimate instance of the class you are casting to. The ClassCastException is thrown to indicate that code has attempted to cast an object to a subclass of which it is not an instance. We can deal with the problem of incorrect casting in two ways: Use the exception handling mechanism to catch ClassCastException. Use the instanceof statement to guard against incorrect casting.
  • Design pattern: The “instanceof” and “typecast” constructs are shown for the illustration purpose only. Using these constructs can be unmaintainable due to large if and elseif statements and can affect performance if used in frequently accessed methods or loops. Look at using visitor design pattern to avoid these constructs. (Refer Q11 in How would you go about section…).
  • We can also get a ClassCastException when two different class loaders load the same class because they are treated as two different classes.