接口也能够创建对象?解决思路

   阅读
接口也能够创建对象?
最近整理以前的代码,发现了如下的代码。
可是一查api,发现FileFilter   竟然是个接口,接口怎么能创建对象?

google了一把,说是匿名内部类
我的理解是FileFilter()   {。。。}一大段实现了接口,然后再用new创建对象。
不知道是不是这样,大家说说。谢谢!!


FileFilter   fileFilter   =   new   FileFilter()   {
public   boolean   accept(File   pathname)   {
String   tmp   =   pathname.getName().toLowerCase();
if   (tmp.endsWith( ". "   +   "vb "))   {
return   true;
}
return   false;
}
};

------解决方案--------------------
是的


------解决方案--------------------
接口可以定义对象,要想new 的话,必须是实现的该接口的实现类
------解决方案--------------------
This is called "anonymous inner class ".

FileFilter fileFilter = new FileFilter() {
public boolean accept(File pathname) {
String tmp = pathname.getName().toLowerCase();
if (tmp.endsWith( ". " + "vb ")) {
return true;
}
return false;
}
};

This segment of code defines an anonymous impementation class for interface FileFilter, then creates an instance of this class, finally assign the instance to a reference variable typed as FileFilter.

You can read books/chapters about inner class for more examples.
------解决方案--------------------
interface A {
public void f();
}
public class Test {
A a = new A() {public void f() {return;}};
}

A a的时候只是声明a为A类型
而new A() {public void f() {return;}};的时候实际上产生了一个匿名类(如果你查看一下编译后的结果,会发现有一个Test$1.class的文件,就是这个东东,后面的数字是自动编号的),而a所指的具体对象就是Test$1这个类型的对象。

接口不能创建对象,创建的只是实现这个接口的匿名类的对象。
阅读