【发布时间】:2013-07-06 14:44:27
【问题描述】:
我有一个问题。基于 Java 7 API Collection 是一个接口,但它带有一些具体的方法,例如 size()。我不明白,该接口如何包含已实现的方法。如果那是一个抽象类是有道理的。 最好的问候
【问题讨论】:
标签: java api interface abstract-class
我有一个问题。基于 Java 7 API Collection 是一个接口,但它带有一些具体的方法,例如 size()。我不明白,该接口如何包含已实现的方法。如果那是一个抽象类是有道理的。 最好的问候
【问题讨论】:
标签: java api interface abstract-class
Collection 是一个接口,但它带有一些具体的方法,例如 size()。
这不是真的。您已经知道的 interface 只是定义了契约,并将实现留给实现它的类。如果你指的是类似的东西
Collection<String> collection = new ArrayList<String>();
System.out.println("Size of the collection is: " + collection.size());
请注意,size() 实现是由 ArrayList 而不是 Collection 提供的。
【讨论】:
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();
【讨论】:
没有任何方法的具体实现。您所指的方法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();
【讨论】:
abstract