I was doing a short research on type casting , below is the mine code
interface Foo {}
class Alpha implements Foo {}
class Beta extends Alpha {}
public class Delta extends Beta
{
public static void main( String[] args )
{
Beta x = new Beta();
Alpha a = x;
// Foo f = (Alpha)x;// --> commented out
Beta b = (Beta)(Alpha)x;
Foo f = (Delta)x; // --> complie time error
}
}
As indicated in the last statement it throws a run time error java.lang.ClassCas tException, please advise and if I cast it with Alpha then it works perfectly fine.
You can not downcast a variable to type that is deeper in the class hierarchy than the actual object. That is because some attributes will need to be added to the downcasted variable and it is not clear what their values should be.
However in all checks regarding the casts what really matter is the actual type of the referenced object, not the currently declared type. For example, even though you have
Alpha a = x;, this will still be downcastable toBeta, because the real instance points to object ofBeta.