Huy Than
Huy Than

Reputation: 1546

Type mismatch: cannot convert from ASuperClass to ASubClass

When I have thes codes:

ASuperClass super1 = new ASuperClass(); 
ASubClass sub1 = new ASubClass(3); 
sub1 = (ASubClass) super1; // this line compiled ok BUT has runtime Error  LINE 3 
ASubClass sub2 = new ASuperClass(); // this line compiled NOT ok  LINE 4

My question is that why is the error in line 3 ("ASuperClass cannot be cast to ASubClass") in line 3 is Runtime Error but not a compile Error similar to the error in Line 4 , which is a compile error. What is the logics behind that? Many thanks!

Upvotes: 1

Views: 62

Answers (1)

Maroun
Maroun

Reputation: 95958

You're getting a runtime error because you're telling the compiler (by the explicit cast) to trust you that you're not making errors, so it's ignoring the errors and doesn't detect it in compilation time. But when the program runs, you'll get an exception since super1 is actually a ASuperClass and not a ASubClass.

In the second case, you're getting a compilation error since the compiler knows your making a mistake (and you're not telling him to trust you by casting for example).

Upvotes: 5

Related Questions