Introduce some interface usage in Java. (This is not a comprehensive tutorial!)
What is
An interface is an abstract type that contains a collection of related methods with empty bodies and constant variables. It is one of the core concepts in Java.
Animal.java
// a self-defined interfaceinterfaceAnimal {publicvoideat(); // interface method (does not have a body)publicvoidmoving(); // interface method (does not have a body)publicstaticvoidmain(String[] args) {//Animal cat = new Animal(); This is wrong }}
An interface can not be used for instantiating an object. It has to be implemented by a class type first.
A functional interface is any inteface with a single abstract method. For example, the Animal inteface is not a functional interface, but the PPrin.
PPrint.java
// a functional publicinterfacePPrint {publicvoidprint(String msg);}
Lambdas in Java 8
Llambda expressions are introduced in Java 8.
An expression in Java is an implementation of a functionalinterface.
A Lambda expression is an expression that should reside in a code body.
Syntax:
(parameter1, parameter2) -> expression
PPrint.java
publicinterfacePPrint {publicvoidprint(String msg);publicstaticvoidmain(String[] args) {PPrint banner_print = msg ->System.out.println("====================\n"+ msg +"\n====================\n");banner_print.print("Hello World!");//without the lambda expression to impplement an interface in line// or to write a separate implementationPPrint banner_print1 =newPPrint() { @Overridepublicvoidprint(String msg) {System.out.println("====================\n"+ msg +"\n====================\n"); } };banner_print1.print("Hello World!"); }}
Comparator Functional Interface
Demo.java
publicclassDemo {publicstaticvoidmain(String[] args) {/* * A comparator interface is used to order the objects of user-defined classes. * A comparator object is capable of comparing two objects of two different classes. * * Using interfacedemo.lambda expression to instantiate an interface * * And a interfacedemo.lambda expression can only implements an interface with a single abstract method * * * */Comparator<String> stringComparator =newComparator<String>() { @Overridepublicintcompare(String o1,String o2) {returno1.compareTo(o2); } };stringComparator.compare("AB","CD");Comparator<String> stringComparatorLambda = (String o1,String o2) ->o1.compareTo(o2); }}