接口、lambda表达式与内部类
1.比较器
import java.util.Comparator;
/**
* @author zhuangshd
* @date 2021/9/7 23:06
*/
public class LengthComparator implements Comparator<String> {
@Override
public int compare(String first, String second) {
return first.length() - second.length();
}
}
import java.util.Arrays;
/**
* @author zhuangshd
* @date 2021/9/7 23:07
*/
public class Test {
public static void main(String[] args) {
String[] friends = {"apple", "mary", "coco"};
Arrays.sort(friends, new LengthComparator());
System.out.println(friends[1]);
LengthComparator lengthComparator = new LengthComparator();
int compare = lengthComparator.compare(friends[0], friends[1]);
System.out.println(compare);
}
}
2.接口的默认方法
/**
* @author zhuangshd
* @date 2021/9/7 23:17
*/
public interface DefaultComparator {
default String getName() {
return "zhuangshd";
}
}
/**
* @author zhuangshd
* @date 2021/9/7 23:19
*/
public interface DefaultInterface {
default String getName() {
return "zsd";
}
}
/**
* 接口默认方法冲突
*
* @author zhuangshd
* @date 2021/9/7 23:20
*/
public class GetNameTest implements DefaultComparator, DefaultInterface {
@Override
public String getName() {
return "coco";
}
}
3.类单继承多实现接口,定义静态类的扩展性限制在于单继承;回调是一种设计模式;
4.对象克隆
/**
* 克隆,默认浅拷贝
*
* @author zhuangshd
* @date 2021/9/7 23:20
*/
public class GetNameTest implements Cloneable {
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
4.Lambda表达式