1

I was reading about Predicate Interface in Java 8, got stuck at why Java made negate(), and() & or() as default method and not static method

Default methods can be easily overridden in implementing class. As per my understanding, the behavior of these methods should never be changed.

Predicate also have isEqual() method which is static

I understand the purpose of the default method as mentioned here(Purpose of Default or Defender methods in Java 8) i.e: Not breaking client implementation if we add a new method in the interface, lambda impl

But my ques is why not make them static method instead of the default method? Benefits of making it static:

  1. No one can override them
  2. predicate is still Functional Interface (same as default)
  3. Can have lambda implementations for such an interface (same as default)

Found the answer: If we make these methods static, then we will not be able to chain these methods

p1.or(p2) will not be possible

  • 1
    Would you rather write `blah.or(blah)` or `Predicate.or(blah, blah)`? – user2357112 Jun 27 '20 at 07:22
  • 4
    Overridden implementations could be more efficient, too. – user2357112 Jun 27 '20 at 07:24
  • This could be a case where `final default` makes sense, but that's not available: https://stackoverflow.com/q/23453287/14955 – Thilo Jun 27 '20 at 07:46
  • 3
    Does this answer your question? [Purpose of Default or Defender methods in Java 8](https://stackoverflow.com/questions/19998309/purpose-of-default-or-defender-methods-in-java-8) – Ole V.V. Jun 27 '20 at 08:27
  • @OleV.V. Thanks! but it didn't answer my question, have updated my question – JAGRITI BANSAL Jun 28 '20 at 11:31
  • 2
    I have written code where I overrode the `and` and `or` to return a more optimized variant of the combined predicate if both were of the same implementation type. That would not have been possible if this had been a static or final method. – Mark Rotteveel Jun 28 '20 at 12:25
  • 3
    Point 2 and 3 are irrelevant, as they apply to default methods as well. You *can* have lambda implementations for `Predicate`. If you really read the linked Q&A you noticed. So only point 1 remains, default methods can be overridden, static methods can’t. But it’s pure conjecture on your side that not being able to override these methods was an advantage. – Holger Jun 28 '20 at 13:00
  • @Holger: Yes I noticed points 2 and 3 in linked Q&A. But my point of adding them with the benefit of static method is to tell that it also gives same feature as default only point 1 is added advantage – JAGRITI BANSAL Jun 28 '20 at 13:52
  • 1
    Found the answer: If we make these methods static, then we will not be able to chain these methods p1.or(p2) will not be possible – JAGRITI BANSAL Jun 28 '20 at 13:59

0 Answers0