我将一个接口作为匿名实现传递给另一个对象,如下所示:
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));
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:它是如何工作的?如何SomeObject知道没有直接传递给对象的数组(数组不是匿名类的成员).
更新
(抱歉延迟更新)
那些在匿名类中使用的成员变量或方法方法呢?他们不是最终的
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;
}
};
Run Code Online (Sandbox Code Playgroud)
我的问题是它是如何工作的?SomeObject 如何知道未直接传递给对象的数组(数组不是匿名类的成员)。
array为最终版本。匿名类中使用的成员变量或方法方法怎么样?它们不是最终的