tvdhout

Interface instancing (3 ways)

May 15th, 2020 (edited)
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.45 KB | None | 0 0
  1. import java.util.function.BinaryOperator;  
  2. // A BinaryOperator Represents an operation upon two operands of the same type, producing a result of the same type
  3. // as the operands. This interface contains one method "apply".
  4.  
  5. /**
  6.  * Class that implements BinaryOperator<Boolean> to perform the "or" operation on two booleans.
  7.  */
  8. class Or implements BinaryOperator<Boolean>{
  9.     @Override
  10.     public Boolean apply(Boolean b1, Boolean b2) {
  11.         return b1 || b2;
  12.     }
  13. }
  14.  
  15. public class Main {
  16.     // 1 -------------------
  17.     // Using a fully defined class "Or" (see above)
  18.     BinaryOperator<Boolean> or = new Or();
  19.  
  20.     // 2 -------------------
  21.     // Using an anonymous class (No class name; looks like you're making an instance of this interface. In this case you
  22.     // must implement all methods of the interface in the body:
  23.     BinaryOperator<Boolean> implies = new BinaryOperator<Boolean>() {
  24.         @Override
  25.         public Boolean apply(Boolean b1, Boolean b2) {
  26.             return !b1 || b2;
  27.         }
  28.     };
  29.  
  30.     // 3 -------------------
  31.     // Using a lambda expression to implement an instance of this interface is possible for any Functional Interface.
  32.     // A functional interface is an interface with just one abstract method. See the @FunctionalInterface annotation
  33.     // in the definition of BinaryOperator; this prevents the interface from defining more than one method.
  34.     BinaryOperator<Boolean> and = (b1, b2) -> b1 && b2;
  35. }
Add Comment
Please, Sign In to add comment