up with some examples & causes of different kinds of errors regarding casting and polymorphism
given B extends A
((B) new A())
will cause a runtime error, right?
and say C doesn't extend anything
(C(new A()))
B ba = new A()
will cause a compile time error
so
are there any more cases like this im not thinking about that would result in compile/runtime errors?
also if u can provide an intuition behind those that'd be appreciated thanks
A casted to B is just regular downcasting. It won't cause an error
isn't there a scenerio in which this'll cause an error?
If B didn't extend A Java would've thrown a ClassCastException which is a RuntimeException
i was sure im missing something. sure there aren't any small annoyances regarding casting in between classes with is a relation between them?
I don't think so. Primitives are all numeral types so it's just a matter of widening and narrowing. As for references, classes with parent-(grand)child relations can be casted, you lose fields and methods upcasting but since children can't make inherited fields and methods less visible it just can't go wrong. The only slightly problematic one is downcasting which you can prevent at compile time using instanceof
umm can you give an example for such problematic downcasting?
Обсуждают сегодня