I am passing an interface as anonymous implementation to a different object like this:
public interface Interface {
public int convert (int a);
}
public static void main(String[] args) throws IOException, InterruptedException {
final int[] array = {1,6,3,5,7,8,4,0,3};
Interface inter = new Interface() {
public int convert(int a) {
int result = a;
for (int i = 0; i < array.length; i++) {
a=a+array[i];
}
return a;
}
};
SomeObject ty = new SomeObject ();
ty.Test(7, inter);
}
public class SomeObject {
public void Test(int number, Interface inter) {
System.out.println(inter.convert(number));
}
}
My question is: how does it work? How does SomeObject
know about the array which is not passed directly to the object (array is not a member of the anonymous class).
Update
(sorry for late update)
what about member vars or methods methods that are used in the anonymous class? they are not final
Interface inter = new Interface() {
public int convert(int a) {
int result = a + someMemberVar;
for (int i = 0; i < array.length; i++) {
a=a+array[i];
}
return a;
}
};