Java Novice Learning Guide [day23] --- New Features of Java 8

1. Members in the interface

1. Member variables: The default is modified by public static final

2. Abstract method: The default is public abstract modification, and there is no method body

3. The default method: modified by default to implement the class object. Method name (); and can be directly called without copying

4. Static method: modified by static, call: interface name. method name (actual parameter); at the same time, note that static methods cannot be inherited by sub-interfaces and cannot be overridden by the implementation class and called directly

2. Functional interface

Definition: There is one and only one abstract method in the interface, but there can be multiple non-abstract methods, which are marked by @FunctionalInterface

@FunctionalInterface
public interface FunctionalInterfacePra {
    
    
	//抽象方法
	void get();
	//静态方法
	public static void test1(){
    
    }
	//默认方法
	public default void test2(){
    
    }
}

3. Lambda expression

Prerequisite: When using lambda, the interface must be a functional interface

//语法
函数式接口  变量名 = (参数1,参数2...) -> {
    
    
                    //方法体
     }

Benefits: 1. Make the code cleaner

2. Focus on the method body

3. No new bytecode files will be generated

Requirements for lambda expression shorthand:

1. = The type on the right will be automatically inferred based on the functional interface type on the left;
2. If the formal parameter list is empty, just keep ();
3. If there is only one formal parameter, () can be omitted, and only the parameter is required The name is
enough ; 4. If the execution statement has only one sentence and no return value, {} can be omitted, if there is a return value, if you want to omit {}, you must omit return at the same time, and the execution statement is guaranteed to have only one sentence ;
5. The data type of the formal parameter list will be inferred automatically;
6. The lambda will not generate a separate internal class file;
7. If the lambda expression accesses the local variable, the local variable must be final, if the local variable is not added The final keyword, the system will automatically add, and then modify the local variable, an error will be reported;

Refer to the constructor in the lambda:

//语法
类名::new//会根据抽象方法的形参顺序,自动在给定的类中寻找构造方法进行匹配
相当于:() -> {
    
    }

Refer to static methods in lambda:

//语法
类名::静态方法名;
相当于:() -> {
    
    }
public class LambdaTest {
    
    
	@Test
	public void testName() throws Exception {
    
    
		List<Object> arrayList = new ArrayList<>();
		arrayList.add("张三");
		arrayList.add("张三2");
		arrayList.add("张三3");
		arrayList.forEach(System.out::println);
	}
}

Guess you like

Origin blog.csdn.net/WLK0423/article/details/109813353
Recommended