gpt4 book ai didi

java - 通过匿名类

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:52:10 26 4
gpt4 key购买 nike

我将一个接口(interface)作为匿名实现传递给另一个对象,如下所示:

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));
}
}

我的问题是:它是如何工作的? 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;
}
};

最佳答案

My question how does it work? How SomeObject knows about the array which is not passed directly to the object (array is not a member of the anonymous class).

  • 回答:不是;除非你将 array 声明为 final。
  • 推理: 它有效(如果数组是最终的)因为它是最终的,它可以被视为常量,因为匿名函数知道该数组不能更改。

what about member vars or methods methods that are used in the anonymous class? they are not final

  • 回答:创建匿名类时,实例变量和方法(以及静态变量和方法)无论如何都在范围内。

关于java - 通过匿名类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8577779/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com