Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why in Java incompatibility of types to casting is checked at runtime and type mismatch to converting at compile time?

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!

like image 358
Alex Avatar asked Dec 26 '22 04:12

Alex


1 Answers

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.

like image 91
Apurv Avatar answered Apr 09 '23 13:04

Apurv