This is simple java program of anonymous class where class is redefined (not interface) as anonymous class.
class Anonymous {
int i = 10;
void main() {
System.out.println("Anonymous Main " + i);
}
void setI(int i) {
System.out.println("under set");
this.i = i;
}
void main2() {
setI(30);
System.out.println("Main 2's " + i);
}
}
public class Runner {
public static void main(String[] args) {
Anonymous a = new Anonymous() {
int i = 20;
@Override
void setI(int i) {
System.out.println("Over set");
this.i = i;
}
@Override
public void main() {
setI(0);
System.out.println("Redefined Anonymous Main " + i);
}
};
a.main();
a.main2();
}
}
Output:-
Over set
Redefined Anonymous Main 0
Over set
Main 2's 10
I have few questions:
In
main2, why it has access toiwith10value?Why object
ahas two copies ofi?If has, then when calling
setIwhy there is not two copies ofsetI?Why
main2access to redefinedsetIand noti?What exactly is Java doing?
I think you should start from reading this part of Oracle guides. Then I hope it will all be a bit more transparent for you. The thing you should understand is that
iin the parent andiin the child are not the same at all.So, regarding your questions:
main2() is not overridden, therefore JIT will use the parent's version of the method using its visibility context of course. The parent does not know about the child's variable
i. Only the child knows that it has hidden the parent field. Therefore your parent prints it'si(not the same as child'si), but thesetIis overridden, and thussetIsets the value of the child'si.Because this is how Java works :) Provided link already
Because the method in the child overrides the one in the parent. It is not hiding in this case, it is true polymorphism.
Becuase you are invoking
main2()on object that has overriddensetI. Therefore it invokes overridden version ofsetI. Again - wheniis modified insidemain2, it is not the sameias in the child, andmain2()in parent has no access to child'si.Just obeying the JLS :) This is expected behavior, I hope now you understand why.