posted 18 years ago
Dear Ganesh Kumar,
Taking your code from this point:
Now class A has these variables: i, j, k
class B has this variable: k
Lets break down the program into simple steps:
When you call sub.i=82, the compiler checks for a variable i in class B, it does not find any! So it travels one step higher in inheritance tree to class A and finds the variable i, so it assigns the value 82 to that variable.Same process takes place as above for the statement sub.j=32Now when it encounters sub.k =10, the compiler finds k in class B itself so value of k is assigned there. REMEMBER THIS STEP!!!When it reached sub.showij(), the compiler checks for this method, does not find any, so it proceeds to class A. It finds the method there.
Now pay close attention, this is the important part. The showij() method USES variables found in class A, and does NOT refer to variables found in the subclass!
Now, if you see the third step again, you will notice that the compiler assigned the value of 10 to variable k of class B and NOT class A. So, by default, the value of k in class A is initialized to 0 and that is what you get in your output.But, if you call sub.showk() method, then the compiler uses the k variable of class B.
[ July 09, 2007: Message edited by: Shyam Prasad Murarka ]
With Best Regards,
Shyam Prasad Murarka