Java这个接口代码实际上如何工作?

时间:2011-01-14 16:11:21

标签: java

我已经使用其他成员给我的想法然后更改了几个容器来汇总下面的代码。对于我的生活,我真的无法理解其中的一些。代码的原因是我希望将函数作为参数传递。我特别不理解的代码部分是:

doFunc(numbers, new IFunction() { 
    public void execute(Object o) { 
       Integer anInt = (Integer) o; 
       anInt++;
       System.out.println(anInt);
    } 
}); 

我在某种程度上理解我们正在使用一个接口来表示一个使用对象的函数(我认为?)。这是完整的代码:

public static void main(String[] args) {
    Integer[] strArray = new Integer[]{1,2,3,4,5};

    List numbers = Arrays.asList(strArray);
    doFunc(numbers, new IFunction() { 
        public void execute(Object o) { 
           Integer anInt = (Integer) o; 
           anInt++;
           System.out.println(anInt);
        } 
    }); 
    for(int y =0; y<numbers.size();y++){
        System.out.println(numbers.get(y));
    }
}

public static void doFunc(List c, IFunction f) { 
   for (Object o : c) { 
      f.execute(o); 
   } 
}

public interface IFunction { 
    public void execute(Object o); 
} 

我想我只需要有人慢一点解释它。谢谢你的支持。

3 个答案:

答案 0 :(得分:5)

这是一个匿名的内部阶级。你可以做到如下:

public static void main(String[] args) {
    Integer[] strArray = new Integer[]{1,2,3,4,5};

    List numbers = Arrays.asList(strArray);
    doFunc(numbers, new ConcreteFunction()); 
    for(int y =0; y<numbers.size();y++){
        System.out.println(numbers.get(y));
    }
}

public static void doFunc(List c, IFunction f) { 
   for (Object o : c) { 
      f.execute(o); 
   } 
}

public interface IFunction { 
    public void execute(Object o); 
} 

public class ConcreteFunction implements IFunction {
    public void execute(Object o) { 
       Integer anInt = (Integer) o; 
       anInt++;
       System.out.println(anInt);
    } 
}

不同之处在于,具体类是可重用的,而匿名内部类则不可用。

另见:

答案 1 :(得分:1)

这里的主要概念是,由于你传递给doFunc的第二个对象是匿名,你不需要在这里实例化一个对象 - 只是界面。以下是代码的每个部分所说的内容:

public interface IFunction { 
    public void execute(Object o); 
}

这表示实现接口IFunction的任何对象都有一个方法execute,它在另一个对象上运行。

public static void doFunc(List c, IFunction f) { 
   for (Object o : c) { 
      f.execute(o); 
   } 
}

此函数采用List c任何实现IFunction 的Object,然后运行execute方法 - 保证在IFunction接口的第二个对象中 - 结束c中的所有对象。

    doFunc(numbers, new IFunction() { 
        public void execute(Object o) { 
           Integer anInt = (Integer) o; 
           anInt++;
           System.out.println(anInt);
        } 
    });

来自main的此代码段获取一个数字列表,并在就地创建一个匿名对象,它实现了IFunction接口。由于它不是任何具体的对象类型,因此它不需要任何其他方法,只需execute,它就是内联定义的。

最终结果是在doFunc的调用中声明的IFunction对象实际上是仿函数 - 它是一个一次性对象,它封装了一个函数,该函数可以在一个列表中运行对象。

答案 2 :(得分:0)

在这种情况下,IFunction指定实现接口的任何人必须定义的接口。

public void execute(Object o);

这意味着任何作为IFunction的对象都有此方法。在您的示例中定义的匿名IFunction将其参数转换为整数,然后递增它并打印该值。

由于doFunc需要一个对象List和一个实现IFunction的对象,main中的调用传递numbers,一个数字列表,以及一个递增它们并打印其值的匿名IFunction。

然后,

doFunc将这些对象放在列表中,并将它们作为参数传递给IFunction f。

相关问题