内部类就是在一个类中定义另外一个类,内部类最大的用途实现方法的回调(CallBack),再进一步就是事件驱动。下面举一个方法的回调的例子:
首先创建一个接口ICallBack.java,内容如下:
package zxm.test;
public interface ICallBack {
public abstract void execute(Object obj) throws Exception;
}
然后,定义一个类TestCallBack.java,这个类用到了上面的接口,内容如下:
package zxm.test;
public class TestCallBack {
// 这个方法用到了ICallBack接口
public void print(String[] names, ICallBack callback) {
try {
for (int i = 0; i < names.length; i++) {
callback.execute(names[i]);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
最后,定义测试类TestInnerAndCallBack.java,内容如下:
package zxm.test;
public class TestInnerAndCallBack {
private TestCallBack testCallBack;
// 这个方法调用了TestCallBack的print方法,而TestCallBack的print方法
// 又回调了这个类的内部类MyCallBack的execute方法。
public void printTest(String[] names) {
class MyCallBack implements ICallBack {
public void execute(Object obj) throws Exception {
// 在这里可以做你要做的事情
System.out.println("Printed this name : " + (String)obj + " by TestCallBack's inner class.");
}
}
this.getTestCallBack().print(names, new MyCallBack());
}
public static void main(String[] args) {
TestInnerAndCallBack testInnerAndCallBack = new TestInnerAndCallBack();
testInnerAndCallBack.setTestCallBack(new TestCallBack());
testInnerAndCallBack.printTest(new String[]{"testName1", "testName2", "testName3", "testName4"});
}
/**
* @return Returns the testCallBack.
* @author Pure Zhou 2006/11/30
*/
public TestCallBack getTestCallBack() {
return testCallBack;
}
/**
* @param testCallBack The testCallBack to set.
* @author Pure Zhou 2006/11/30
*/
public void setTestCallBack(TestCallBack testCallBack) {
this.testCallBack = testCallBack;
}
}
运行测试类,最后的结果如下:
Printed this name : testName1 by TestCallBack's inner class.
Printed this name : testName2 by TestCallBack's inner class.
Printed this name : testName3 by TestCallBack's inner class.
Printed this name : testName4 by TestCallBack's inner class.