Originally posted by Arun Pai:
pls help to explain the sequence
Note that neither class extends the other, so the methods will be picked up strictly based on reference type:
Let's keep a record of x.x and x.y values after each statement:
>>> x.x = 0, y.x = 0 //class initialization
A x = new A(20);
>>> x.x = 20, y.x = 0
B y = new B();
>>> x.x = 20, y.x = 10
System.out.println(x.x); >>> prints 20
x.m1(y); // m1 in A is invoked because x is instanceof A
>>> x.x = 10, y.x = 11
System.out.println(x.x); >>> prints 10
y.m1(30); // m1 in B is invoked because y is instanceof B
>>> x.x = 10, y.x = 30
System.out.println(y.x); >>> prints 30
((A)x).m1(y); // The casting does nothing. m1 in A is invoked
>>> x.x = 30, y.x = 31
System.out.println(y.x); >>> prints 31