有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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();
}

我们可以在构造函数中实现接口吗?(线程类,可运行接口)。有谁能帮助我理解它背后的概念,或者建议一些文章来研究这个概念? 先谢谢你


共 (5) 个答案

  1. # 1 楼答案

    命令new只能在这样的情况下与接口一起使用,您可以立即定义方法

  2. # 4 楼答案

    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();
    

    new Runnable() {...}正在声明一个Anonymous Inner Classes

  3. # 5 楼答案

    在您的示例中,您没有在构造函数中创建接口

    该代码段显示了Runnable的匿名子类的实现匿名,因为该类的类型根本没有名称

    new Runnable(...语句创建对该匿名类实例的引用,并且该引用被传递给构造函数Thread(Runnable r)


    注意-我们可以通过三个步骤完成相同的操作,这更容易理解:

    // create an anonymous implementation of Runnable
    Runnable r = new Runnable() {
         @Override
         public void run() {
           // the run implementation
         }
       };
    
    // create a Thread
    Thread t = new Thread(r);
    
    // start the Thread -> will call the run method from the Runnable
    t.start();