Our website loads in split second powered by Schema Theme. Thanks to MyThemeShop

Why Type casting in java–Understanding core concepts

Type casting in java

As we have discussed in the previous post, Object is the super class for all classes in java.Now let’s see Why Type Casting required, when we use Object class. If we are calling a method on the reference, it must be there in the corresponding reference type and don’t consider about the object creation

The below code is not applicable as object means String and length is not there in the Object class, so the below code is wrong.

 

Write the following code instead

If super class reference variable is pointing to subclass object then we can type cast super class reference variable to subclass reference variable.

 The below code is wrong.

|—>If the super class reference variable is pointing to the super class object then we can’t type cast the super class reference variable to subclass reference variable and it is not possible in java.                                                       |—>The above code doesn’t throw compile time error, it will throw runtime error [ClasscastException]

Download Source for Eclipse |WhyTypeCast-2