First, let's look at first code. Expression "this.s1" is clear for everybody I guess. Then we cast "this" like this "((C)this)". Now what we have here? Reference to object of type "C". We could do it like this:"C c = this;". This is legal beacuse "this" is an object of type D and D is a subclass of C. So far so good.
Now we trying to access s1 variable."((C)this).s1" is equal to "C c = this; c.s1". But we have more then one s1 (one in D class and enother in C class). Which one will be accessed?
Compiler sees the type of referens variable (which is type C) and bound s1 with variable which is declared in C class. And, as a result, you get value of s1 from C class (which is "C").
Let's take a look on the second piece of code.
This story is complete different. Then you call "((C)this).m1();" it is equal to "C c = this; c.m1();". But for now which method will be invoked will be solved at runtime, by JVM not by a compiler. So, JVM looks at you object and founds that the type of it is D!!! And JVM calls method m1() from D class. So, you get your "DDDD" output.
(Now I'm gonna kill myself for explanation of that kind
)
P.S. Answers are correct.
[ July 19, 2005: Message edited by: George Bolyuba ]