使用匿名内部类(匿名内部类可参考)
interface Command { void process(int[] target); } class ProcessArray { public void process(int [] target, Command cmd) { cmd.process(target); } } public class CommandTest { public static void main(String[] args) { ProcessArray pa = new ProcessArray(); int[] arr = {1,2,3,4}; //使用匿名内部类 pa.process(arr, new Command(){ public void process(int[] arr) { int sum =0; for(int k : arr) sum += k; System.out.println(sum); } } ); } }
使用Lambda表达式,可以简化匿名内部类。(部分可以用Lambda表达式代替)
interface Command { void process(int[] target); } class ProcessArray { public void process(int [] target, Command cmd) { cmd.process(target); } } //Java8 新增了Lambda表达式,Lambda表达式完全可用于简化匿名内部类对象 public class CommandTest { public static void main(String[] args) { ProcessArray pa = new ProcessArray(); int[] arr = {1,2,3,4}; //使用Lambda表达式 pa.process(arr, (int[] arr1)-> //不能重复arr,错误: 已在方法 main(String[])中定义了变量 arr { int sum =0; for(int k : arr1) sum += k; System.out.println(sum); } ); } }
原文:https://www.cnblogs.com/htj10/p/12366065.html