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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…