java - Type mismatch: cannot convert from ASuperClass to ASubClass -
when have thes codes:
asuperclass super1 = new asuperclass(); asubclass sub1 = new asubclass(3); sub1 = (asubclass) super1; // line compiled ok has runtime error line 3 asubclass sub2 = new asuperclass(); // line compiled not ok line 4
my question why error in line 3 ("asuperclass cannot cast asubclass") in line 3 runtime error not compile error similar error in line 4 , compile error. logics behind that? many thanks!
you're getting runtime error because you're telling compiler (by explicit cast) trust you're not making errors, it's ignoring errors , doesn't detect in compilation time. when program runs, you'll exception since super1
asuperclass
, not asubclass
.
in second case, you're getting compilation error since compiler knows making mistake (and you're not telling him trust casting example).
Comments
Post a Comment