Hi Anshul (and everybody else)
in my view 3 general rules apply her:
1. A reference can only point to objects either
a. has the same type as the reference self
b. is a subtype of the reference's type
2. With a reference can you only access fields and methods which
a. are declared as the same type as the reference (class or
interface)
b. are declared as a super-type to the type of the reference
3. No matter what the type of the reference is; it is the method
closest to the object's own type, that get to be executed.
in relation to your (fun) program I see a possible explanaition as this:
obj1 ia reference of type class1, that never changes.
when obj1=obj is executed, obj1 points to an object of type class2 ( a subtype.)
When obj1.showTxt(obj2); gets called the following happens:
1. the reference obj1 of type class1 does not know of a method called void showTxt(class2), so the argument obj2 of type class2 get upcastet to type class1. So the method showTxt(class1) in class1 gets executed, printing "in class1".
I relation to the 3 rule, I think no. 2 is the one to focus on here.
I'am no expert, I have just been fighting this very problem in a school assignment recently.
I hope I didnt add to the confusion.
Regards
Christian