Let's say there are 2 classes. And Child
extends Parent
.
public class Parent {}
and
public class Child extends Parent {}
I know that the following code is incorrect:
Child obj = new Parent(); // causes java.lang.Error
or
Child obj = (Child) new Parent(); // causes java.lang.ClassCastException
But I don't understand why I get a compile error in the first case and runtime exception in the second case. After all, a parent can never be convert or cast to child. Why second of these cases is not checked at compile time?
I would be very grateful for a clear and reasonable idea!
Child obj = new Parent();
In this case the compiler tries to check (implicit cast) if Parent
object can be set to Child
reference and when this casting fails, you get compile time error.
Child obj = (Child) new Parent();
In this case the compiler sees that you are explicitly casting Parent
object to Child
, so compiler leaves it for the runtime to decide if the casting is valid, in a sense the developer takes the responsibility of the casting. So if this casting fails, you get a runtime error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With