Java 8 new features-interfaces and Lambda expressions, java8lambda
Compared with the previous version (Java 7), the new features of Java 8 are mainly reflected in two aspects:
1. Interface Definition and use
2. Lambda expressions simplify the use of anonymous internal classes.
Java 8 features:
1. embodiment in the interface
(1) An object method can be defined in an interface, but only two methods can be defined except the original abstract method:
A. Public static methods
For example:
package com.jasberyon.java8.interfacer;public interface InterfaceA {public static void sayHi(){System.out.println("InterfaceA---sayHi");}}
Note that:
A. Because static methods belong to Classes (files), you must use the corresponding interface (class where static methods are located) to call them. Therefore, when calling static methods in an interface in Java 8, you can only call the method using the interface name.
B. General Methods declared using the default keyword
For example:
<span style="font-size:12px;">package com.jasberyon.java8.interfacer;public interface InterfaceA {public default void sayHi2(){System.out.println("InterfaceA---sayHi2");}}</span>
Note that:
B. The default keyword can only be used in the interface. In this case, you need to remove the default keyword when re-writing the method of the Key Identifier of the default in the specific implementation class of the interface. For example:
package com.jasberyon.java8.interfacer;public class InterfaceImpl implements InterfaceA {public static void main(String[] args){InterfaceA.sayHi();InterfaceImpl.sayHi();}public static void sayHi(){System.out.println("InterfaceImpl---sayHi");}public void sayHi2(){System.out.println("InterfaceB---sayHi2");}}
In the code above (the method marked by the default keyword in the rewrite Interface), when a multi-state call is performed, the method of the real class (subclass) is also used. If the method is not rewritten, the default method in the interface is used.
For example:
package com.jasberyon.java8.interfacer;public class InterfaceImpl implements InterfaceA {public static void main(String[] args){InterfaceA.sayHi();InterfaceImpl.sayHi();InterfaceA ia = new InterfaceImpl();ia.sayHi2();}public static void sayHi(){System.out.println("InterfaceImpl---sayHi");}public void sayHi2(){System.out.println("InterfaceB---sayHi2");}}
Output result:
InterfaceA --- sayHi
InterfaceImpl --- sayHi
InterfaceB --- sayHi2
Note: in Java, classes are individually inherited, while interfaces can be implemented in multiple ways. The original intention is to consider security. In the multi-inheritance mode, if subclass C inherits the parent class A and B, and A and B have the same method methodAlike. In this case, the method in the parent class that is used in subclass C cannot be distinguished. The (originally designed) interfaces are different. The implementation class must implement the methods defined in the interface, so the preceding security problems do not exist.
Now the problem is: because non-static methods can be defined in interfaces in the new features of Java 8, when the same non-static default method is defined in multiple interfaces, if the Implementation class implements these multiple interfaces, will there be more inheritance?
The answer is:Negative
In this case, a compilation error occurs. You must overwrite all the methods defined in the same interface in the implementation class.
For example:
Define interface InterfaceA
package com.jasberyon.java8.interfacer;public interface InterfaceA {public static void sayHi(){System.out.println("InterfaceA---sayHi");}public default void sayHi2(){System.out.println("InterfaceA---sayHi2");}}
Define interface InterfaceB
package com.jasberyon.java8.interfacer;public interface InterfaceB {public static void sayHi(){System.out.println("InterfaceB---sayHi");}public default void sayHi2(){System.out.println("InterfaceB---sayHi2");}}
In this case, the InterfaceA and InterfaceB interfaces have the same method:PublicdefavovoidSayHi2 (), then the implementation class must rewrite the same method.
Implementation class InterfaceImpl
package com.jasberyon.java8.interfacer;public class InterfaceImpl implements InterfaceA, InterfaceB {public static void sayHi(){System.out.println("InterfaceImpl---sayHi");}public void sayHi2(){System.out.println("InterfaceB---sayHi2");}}
Summary: Java interfaces are used for extensions. in Java 8, it is meaningless to avoid overwriting interfaces with multiple default methods. Java 8's new features in interfaces are only used as an extension. For static methods in the interface, it is meaningless to "Override" (not actually) in the Implementation class.
2. Lambda expressions simplify the use of anonymous internal classes
Lambda expressions replace the original writing of anonymous internal classes, which simplifies the use of anonymous internal classes. Of course, the simplified method always limits the function usage. The Just like enhanced for (for-each) loop.
Syntax structure of Lambda expressions:
(Parameter 1, parameter 2...)-> {
Override method content without specifying the method name.
}
(1) Use Lambda expressions for Multithreading
The original example of using anonymous internal classes to implement multithreading:
Package com. jasberyon. java8.lambda; public class ThreadDemo {public static void main (String [] args) {new Thread (new Runnable () {@ Overridepublic void run () {for (int I = 0; I <200; I ++) {System. out. println ("run ---------" + I );}}}). start (); for (int j = 0; j <200; j ++) {System. out. println ("execute mian ---------------" + j );}}}
After Lambda expressions are transformed:
Package com. jasberyon. java8.lambda; public class ThreadDemo {public static void main (String [] args) {Runnable runnable = ()-> {for (int I = 0; I <200; I ++) {System. out. println ("run ---------" + I) ;}}; new Thread (runnable ). start (); for (int j = 0; j <200; j ++) {System. out. println ("execute mian ---------------" + j );}}}
Or write as follows:
Package com. jasberyon. java8.lambda; public class ThreadDemo {public static void main (String [] args) {new Thread ()-> {for (int I = 0; I <200; I ++) {System. out. println ("run ---------" + I );}}). start (); for (int j = 0; j <200; j ++) {System. out. println ("execute mian ---------------" + j );}}}
The drawbacks of Lambda are also obvious. If multiple abstract methods are defined in an interface, you can only use the traditional method.
(2) Use the Lambda expression in the Set sorting "comparator"
TreeSet sorts the strings in the natural order, as shown in the following code:
package com.jasberyon.java8.lambda;import java.util.Set;import java.util.TreeSet;public class TreeSetDemo {public static void main(String[] args) {Set<String> set = new TreeSet<String>();set.add("asdafa");set.add("abcdefsadf");set.add("sahdfoad");set.add("bhsayuadasdfasdf");set.add("auiweyqwergeawgfasdasd");System.out.println(set);}}
Result output:
[Abcdefsadf, asdafa, auiweyqwergeawgfasdasd, bhsayuadasdfasdf, sahdfoad]
After using a custom comparator:
package com.jasberyon.java8.lambda;import java.util.Comparator;import java.util.Set;import java.util.TreeSet;public class TreeSetDemo {public static void main(String[] args) {Set<String> set = new TreeSet<String>(new MyCompareMethod());set.add("asdafa");set.add("abcdefsadf");set.add("sahdfoad");set.add("bhsayuadasdfasdf");set.add("auiweyqwergeawgfasdasd");System.out.println(set);}}class MyCompareMethod implements Comparator<String>{@Overridepublic int compare(String o1, String o2) {int length = o1.length() - o2.length();return length == 0?o1.compareTo(o2):length;}}
Result output:
[Asdafa, sahdfoad, abcdefsadf, bhsayuadasdfasdf, auiweyqwergeawgfasdasd]
After using an anonymous internal class:
package com.jasberyon.java8.lambda;import java.util.Comparator;import java.util.Set;import java.util.TreeSet;public class TreeSetDemo {public static void main(String[] args) {Set<String> set = new TreeSet<String>(new Comparator<String>(){@Overridepublic int compare(String o1, String o2) {int length = o1.length() - o2.length();return length == 0?o1.compareTo(o2):length;}});set.add("asdafa");set.add("abcdefsadf");set.add("sahdfoad");set.add("bhsayuadasdfasdf");set.add("auiweyqwergeawgfasdasd");System.out.println(set);}}
Transform using Lambda expressions:
package com.jasberyon.java8.lambda;import java.util.Set;import java.util.TreeSet;public class TreeSetDemo {public static void main(String[] args) {Set<String> set = new TreeSet<String>((String o1, String o2)->{int length = o1.length() - o2.length();return length == 0?o1.compareTo(o2):length;});set.add("asdafa");set.add("abcdefsadf");set.add("sahdfoad");set.add("bhsayuadasdfasdf");set.add("auiweyqwergeawgfasdasd");System.out.println(set);}}
It can also be written as follows:
package com.jasberyon.java8.lambda;import java.util.Set;import java.util.TreeSet;public class TreeSetDemo {public static void main(String[] args) {Set<String> set = new TreeSet<String>((o1, o2)->{int length = o1.length() - o2.length();return length == 0?o1.compareTo(o2):length;});set.add("asdafa");set.add("abcdefsadf");set.add("sahdfoad");set.add("bhsayuadasdfasdf");set.add("auiweyqwergeawgfasdasd");System.out.println(set);}}
It is worth noting that generic annotation is required at this time. That is, the comparison type must be declared in <>; otherwise, compilation fails.
At the same time, the implementation of Lambda expressions will not produce additional class files (the original method of anonymous internal classes is also to generate files like Ttt $ xx. class.
Many others will not be listed. Remember, when constructing an anonymous internal class, if only one method needs to be rewritten, Lambda expressions can be used.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.