and expected the Compile Time errors will be generated at Lines marked Line 9 and Line 10 as Class A is not implemented Interface I and C is not A. But I see only Line 10 gives the Compile Error not Line 9, Can anybody explain the reason
The detailed rules for compile-time correctness checking of a casting conversion of a value of compile-time reference type S (source) to a compile-time reference type T (target) are as follows:
If S is an interface type:
If T is an array type, then T must implement S, or a compile-time error occurs.
If T is a class type that is not final (§8.1.1), then the cast is always correct at compile time (because even if T does not implement S, a subclass of T might).
If T is an interface type and if T and S contain methods with the same signature (§8.4.2) but different return types, then a compile-time error occurs
Srinivas Katta wrote:It is possibl if we implement the line of code you have given, but that is not included in Original Source. in that Case how Line 9 will not give any compiler Error
But that's not the point. The compiler will only give an error if that cast cannot possibly work. The compiler doesn't try to look at the previous lines and work out whether it will work - it looks at the types and works out whether it could.
Add my class E, and add the line a = new E(); just before line 9, and the cast will be successful. And because it could be successful, the compiler will allow it (and you'll get a run-time exception when it doesn't work).
A a = new E(); //possible
I i = new E(); //possible
I i = new A(); //how come it is possible? - class A has no knowledge about the methods in I, nor does it implement it.
Class A has no knowledge about its subclass E too! I'm just a way too confused, i think!
Don't you go through the Seetharaman Venkatasamy's post? If S(in your case, interface I) is an interface type, and If T(in you case, class A) is a class type that is not final, then the cast is always correct at compile time (because even if T does not implement S, a subclass of T might(in your case, class E)).
Have a look, on you recent post regarding this scenario in the general forum.
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|