0
        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??

8
  • 1
    You can't change the class of an Object, you can only change the class of a reference. Commented Oct 17, 2016 at 10:53
  • i don't understand where i'm trying to change class of object in my code?? Commented Oct 17, 2016 at 11:00
  • When you do (C) b you are trying to pretend this changes the type of the object to a C but it doesn't. The type of the Object is always a B. Commented Oct 17, 2016 at 11:04
  • but B is parent of C it's true ? so C is instanceof B and can i do casting!! Commented Oct 17, 2016 at 11:07
  • 1
    This is explained in many places in the internet already. In all respect for stackoverflowers, I doubt that anything that will be written in this thread will be clearer than what is already out there. Please do your research and study the resources.
    – Anonymous
    Commented Oct 17, 2016 at 11:11

1 Answer 1

6

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 
1
  • You can cast class only to it's parent, but not to it's child. Because class doesn't know anything about sublasses.
    – maxpovver
    Commented Oct 17, 2016 at 11:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.