【问题标题】:Interface and implemented methods接口和实现的方法
【发布时间】:2013-07-06 14:44:27
【问题描述】:

我有一个问题。基于 Java 7 API Collection 是一个接口,但它带有一些具体的方法,例如 size()。我不明白,该接口如何包含已实现的方法。如果那是一个抽象类是有道理的。 最好的问候

【问题讨论】:

    标签: java api interface abstract-class


    【解决方案1】:

    Collection 是一个接口,但它带有一些具体的方法,例如 size()。

    这不是真的。您已经知道的 interface 只是定义了契约,并将实现留给实现它的类。如果你指的是类似的东西

    Collection<String> collection = new ArrayList<String>();
    System.out.println("Size of the collection is: " + collection.size());
    

    请注意,size() 实现是由 ArrayList 而不是 Collection 提供的。

    【讨论】:

      【解决方案2】:

      java.util.Collection 没有实现的方法,它是一个接口。这是size 方法的声明:

      /**
       * Returns the number of elements in this collection.  If this collection
       * contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
       * <tt>Integer.MAX_VALUE</tt>.
       *
       * @return the number of elements in this collection
       */
      int size();
      

      【讨论】:

        【解决方案3】:

        没有任何方法的具体实现。您所指的方法size也没有任何具体的实现。

        /**
         * Returns the number of elements in this collection.  If this collection
         * contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
         * <tt>Integer.MAX_VALUE</tt>.
         *
         * @return the number of elements in this collection
         */
        int size();
        

        【讨论】:

        • 那么,方法size()就是一个抽象方法。一旦你实现了 Collection 接口,你需要重写抽象方法,不是吗?但是还有更多这样的方法。
        • 但是这样的方法还有很多。你是说有实现的方法吗?不可能吧?接口(一般)不能有实现的方法。默认情况下,接口中的所有方法都是abstract
        • 一旦你实现了那个接口,你就继承了这些方法。完成后,您可以对本质上是集合的对象执行操作。这个事实让我很困扰,因为这些方法没有被注释为抽象的。
        猜你喜欢
        • 2020-04-02
        • 2019-01-08
        • 2014-07-11
        • 2020-04-06
        • 1970-01-01
        • 1970-01-01
        • 2011-11-20
        • 1970-01-01
        • 2014-04-12
        相关资源
        最近更新 更多