Android AL-Khatib Android AL-Khatib - 1 year ago 71
Java Question

Down Casting to indirect subclass does not work?

public class A
{

public void printA(){
System.out.println("A");
}

}


public class B extends A
{
public void printB(){
System.out.println("B");
}

}

public class C extends B
{
public void printC(){
System.out.println("C");
}

}

public class test {
public static void main(String[] args)
{

A a = new B();
a.printA(); // work

B b = (B) a;
b.printB(); // work

C c = (C) b;
c.printC(); // not work throw java.lang.ClassCastException

}
}


i have three classes A and B and C

C extends from B and B extends from A

why down casting work from A to B, and does not work from B to C ,although the relation between them like A and B , B is parent of C so how it work JVM??

Answer Source

Classes can only be cast to their parent classes, they have no knowledge about their subclasses.

Since your object is an instance of B, it does not implement methods of C.

This will work:

  A  a = new C();
  a.printA(); // work

  B b = (B) a;
  b.printB(); // work

  C c = (C) b;
  c.printC(); // work