System.out.println("Value of i from class A:" + i); } }
class B extends A { int i = 5; public void valueInt() {
System.out.println("Value of i from class B :" + i);
}
}
Its giving the o/p as:
Value of i from class B :5 Value of i from class B :5 .........0 .........5
When we have assigned A1=B1, then why A1.i and A1.valueInt() are giving different values?
Srikanth Basa
Ranch Hand
Joined: Jun 06, 2005
Posts: 241
posted
0
Aha the old classic problem of which one will be invoked.
Please note that when you call a method on an object, the method is invoked based on the objects Runtime type (i.e. the actual object pointed to by the reference variable).
Whereas when you access a variable, the variable picked up by using the reference type (and not the Runtime type of the actual object)
Thats the reason why you get to see two different values for method vs variable.