Re: Difference between compile time and runtime reference/objects
"lielar" <lielar@gmail.com> wrote in message
news:fef5cfcd-99a4-4897-b0d4-d66bc120517d@i12g2000prf.googlegroups.com...
Hi
I have the following code
-------------------------------------------------
interface I {
int i = 0;
}
class A implements I {
int i = I.i + 1;
}
class B extends A {
int i = I.i + 2;
static void printAll(A obj) {
System.out.println(obj.i);
}
public static void main(String [] args) {
B b = new B();
A a = new B();
printAll(a);
printAll(b);
}
}
You have 2 instance variables both called i, which is almost always a
mistake. printAll() selects the instance variable based on the compile-time
type of the expression, so it always hits the one in A.
You can make printAll print '2' for B by allowing it dispatch through
object. You don't have to overload any methods to do this.
1) add getI () { return i; } to class A
2) replace the duplicate declaration of "i" in B with i = I.i + 2 in its
constructor
3) Make printAll use the method
System.out.println (obj.getI ())
Cheers,
Matt Humphrey http://www.iviz.com/