java有可能在构造函数中实现接口吗?
这个问题可能看起来毫无意义。但是,有谁能向我澄清一下我在这个问题上附加的一些代码吗。我正在做一个与解析相关的大学项目。所以我指的是HtmlCleaner。我被这个编码搞砸了
final CleanerProperties props = new CleanerProperties();
final HtmlCleaner htmlCleaner = new HtmlCleaner(props);
final SimpleHtmlSerializer htmlSerializer =
new SimpleHtmlSerializer(props);
// make 10 threads using the same cleaner and the same serializer
for (int i = 1; i <= 10; i++) {
final String url = "http://search.eim.ebay.eu/Art/2-1/?en=100&ep=" + i;
final String fileName = "c:/temp/ebay_art" + i + ".xml";
new Thread(new Runnable() {
public void run() {
try {
TagNode tagNode = htmlCleaner.clean(new URL(url));
htmlSerializer.writeToFile(tagNode, fileName, "utf-8");
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
我们可以在构造函数中实现接口吗?(线程类,可运行接口)。有谁能帮助我理解它背后的概念,或者建议一些文章来研究这个概念? 先谢谢你
# 1 楼答案
命令
new
只能在这样的情况下与接口一起使用,您可以立即定义方法# 2 楼答案
这是一个匿名类。参考:http://ssmela.googlepages.com/AnonymousClassesinJava.pdf
# 3 楼答案
您正在声明一个匿名类,该类“继承”(或实现,在本例中)一个Runnable
线程只是使用一个现有的线程构造函数(一个接受Runnable的构造函数)。匿名类是Java的一部分(并且已经存在很长时间):http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#252986
# 4 楼答案
new Runnable() {...}
正在声明一个Anonymous Inner Classes# 5 楼答案
在您的示例中,您没有在构造函数中创建接口
该代码段显示了
Runnable
的匿名子类的实现匿名,因为该类的类型根本没有名称new Runnable(...
语句创建对该匿名类实例的引用,并且该引用被传递给构造函数Thread(Runnable r)
注意-我们可以通过三个步骤完成相同的操作,这更容易理解: