接口、lambda表达式与内部类

    1.比较器

    1. import java.util.Comparator;
    2. /**
    3. * @author zhuangshd
    4. * @date 2021/9/7 23:06
    5. */
    6. public class LengthComparator implements Comparator<String> {
    7. @Override
    8. public int compare(String first, String second) {
    9. return first.length() - second.length();
    10. }
    11. }
    12. import java.util.Arrays;
    13. /**
    14. * @author zhuangshd
    15. * @date 2021/9/7 23:07
    16. */
    17. public class Test {
    18. public static void main(String[] args) {
    19. String[] friends = {"apple", "mary", "coco"};
    20. Arrays.sort(friends, new LengthComparator());
    21. System.out.println(friends[1]);
    22. LengthComparator lengthComparator = new LengthComparator();
    23. int compare = lengthComparator.compare(friends[0], friends[1]);
    24. System.out.println(compare);
    25. }
    26. }

    2.接口的默认方法

    1. /**
    2. * @author zhuangshd
    3. * @date 2021/9/7 23:17
    4. */
    5. public interface DefaultComparator {
    6. default String getName() {
    7. return "zhuangshd";
    8. }
    9. }
    10. /**
    11. * @author zhuangshd
    12. * @date 2021/9/7 23:19
    13. */
    14. public interface DefaultInterface {
    15. default String getName() {
    16. return "zsd";
    17. }
    18. }
    19. /**
    20. * 接口默认方法冲突
    21. *
    22. * @author zhuangshd
    23. * @date 2021/9/7 23:20
    24. */
    25. public class GetNameTest implements DefaultComparator, DefaultInterface {
    26. @Override
    27. public String getName() {
    28. return "coco";
    29. }
    30. }

    3.类单继承多实现接口,定义静态类的扩展性限制在于单继承;回调是一种设计模式;
    4.对象克隆

    1. /**
    2. * 克隆,默认浅拷贝
    3. *
    4. * @author zhuangshd
    5. * @date 2021/9/7 23:20
    6. */
    7. public class GetNameTest implements Cloneable {
    8. @Override
    9. protected Object clone() throws CloneNotSupportedException {
    10. return super.clone();
    11. }
    12. }

    4.Lambda表达式