Upcasting Downcasting

后端 未结 5 740
攒了一身酷
攒了一身酷 2020-12-21 17:41

I have a parent class class A and a child class class C extends A.

A a=new A();
C c=(C)a;

This gives me error. Wh

5条回答
  •  一个人的身影
    2020-12-21 17:57

    It's giving you an error because a isn't an instance of C - so you're not allowed to downcast it. Imagine if this were allowed - you could do:

    Object o = new Object();
    FileInputStream fis = (FileInputStream) o;
    

    What would you expect to happen when you tried to read from the stream? What file would you expect it to be reading from?

    Now for the second part:

    A a=new A();
    C c=new C();
    C c=(C)a;
    

    That will not work fine - for a start it won't even compile as you're declaring the same variable (c) twice; if you fix that mistake you'll still get an exception when you try to cast an instance of A to C.

    This code, however, is genuinely valid:

    A a = new C(); // Actually creates an instance of C
    C c = (C) a; // Checks that a refers to an instance of C - it does, so it's fine
    

提交回复
热议问题