1

While looking into the source code of Predicate interface in java I found, it contains few implemented methods like or, and, isEqual. But how a interface can contain non abstract methods?

@FunctionalInterface
public interface Predicate<T> {

    
    boolean test(T t);

  
    default Predicate<T> **and**(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

   
    default Predicate<T> **negate**() {
        return (t) -> !test(t);
    }

    
    default Predicate<T> **or**(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

    
    static <T> Predicate<T> **isEqual**(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }

    @SuppressWarnings("unchecked")
    static <T> Predicate<T> **not**(Predicate<? super T> target) {
        Objects.requireNonNull(target);
        return (Predicate<T>)target.negate();
    }
    }

Could anyone please explain how an interface can contain implemented methods in it?

Thanks

Botje
  • 26,269
  • 3
  • 31
  • 41
  • 2
    dafault and static methods in interfaces were introduced in Java 8, if that is what you are asking. the default methods also enabled the implementation of the stream() methods on the collection classes while keeping the backward compatibility – Pavel Jan 08 '23 at 16:52
  • oh ok thanks @Pavel. One more doubt too what is mean by backward compatibility? – PIRANESH SAKTHIVEL Jan 08 '23 at 16:57
  • see this article for example https://dzone.com/articles/when-to-use-java-8-default-methods-in-interfaces – Pavel Jan 08 '23 at 17:02
  • Does this answer your question? [Why we need default methods in Java?](https://stackoverflow.com/questions/25784417/why-we-need-default-methods-in-java) – Michael Jan 09 '23 at 19:06

0 Answers0