基本概念:接口不是类,而是对类的一组描述
一个类只能继承一个对象,但是可以实现多个接口,因此接口更加常用
通过实现Comparable
接口,使得对象可以排序
public class test02 {
public class Employee implements Comparable<Employee>{
private String name;
private int salary;
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
@Override
public int compareTo(Employee o) {
return Integer.compare(salary, o.salary);
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\\'' +
", salary=" + salary +
'}';
}
}
@Test
public void main1(){
Employee[] employees = new Employee[3];
employees[1] = new Employee("aaa", 111);
employees[0] = new Employee("bbb", 222);
employees[2] = new Employee("ccc", 333);
Arrays.sort(employees);
System.out.println(Arrays.toString(employees));
}
}
接口的特性:接口中不能包含实例域,但是可以包含常量
默认方法:
public class test03 {
public interface Print{
default public void print(){
System.out.println("hello");
}
}
public class Employ implements Print{
@Override
public void print() {
Print.super.print();
}
}
@Test
public void main() {
new Employ().print();
}
}
实现深拷贝,只需要实现Cloneable
接口(这个接口仅仅是一个标记接口),然后实现clone
方法
public void main() {
Integer[] ints = {98, 243, 35, 13, 57, 243};
List<Integer> list = Arrays.asList(ints);
// 之前的排序
list.sort(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
System.out.println(list);
// 使用Lambda表达式
list.sort((o1, o2) -> (o1 - o2));
System.out.println(list);
}
方法的引用,对于这(x)->{System.out.println(x);}
这样更简单的lambda我们可以直接传递方法的引用。
方法引用格式:class:method
@Test
public void main() {
Integer[] ints = {98, 243, 35, 13, 57, 243};
List<Integer> list = Arrays.asList(ints);
// System.out.println();
list.forEach((x)->{
System.out.println(x);
});
System.out.println("----");
list.forEach(System.out::println);
}
背景:
内部类(成员内部类)简单使用:
public class test09 {
private boolean flag = true;
public class Inter{
void print(){
if(flag) {
System.out.println("hello " + flag);
}
}
}
@Test
public void main() {
test09 t = new test09();
Inter inter = new Inter();
inter.print();
}
}