Why the forEach method in Iterable interface is not abstract? [duplicate]

孤街醉人 提交于 2019-12-23 04:43:39

问题


When I see the Iterable interface source, it looks like the foreach method and Spliterator methods are not abstract. How an interface can have non abstract methods? Or is there anything I am missing in this? See the Iterbale interface source below.

package java.lang;

import java.util.Iterator;
import java.util.Objects;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;

public abstract interface Iterable<T>
{
  public abstract Iterator<T> iterator();

  public void forEach(Consumer<? super T> paramConsumer)
  {
    Objects.requireNonNull(paramConsumer);
    Iterator localIterator = iterator();
    while (localIterator.hasNext())
    {
      Object localObject = localIterator.next();
      paramConsumer.accept(localObject);
    }
  }

  public Spliterator<T> spliterator()
  {
    return Spliterators.spliteratorUnknownSize(iterator(), 0);
  }
}
/* Location:           C:\Program Files\Java\jre1.8.0_121\lib\rt.jar
 * Qualified Name:     java.lang.Iterable
 * Java Class Version: 8 (52.0)
 * JD-Core Version:    0.7.1
 */

回答1:


With Java 8 you can define a default implementation in the interface.
It is what java.lang.Iterable does :

public interface Iterable<T> {
    ...    
    default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }
   ...
}

Your actual code doesn't refer the Java 8 source code.



来源:https://stackoverflow.com/questions/42999687/why-the-foreach-method-in-iterable-interface-is-not-abstract

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!