接口方法和抽象方法一样不能实例化,(其实接口方法就是抽象方法了)所以不存在静态代码块、实例代码块、构造方法
接口的方法可以有内容,有内容时候要用default修饰
接口的成员属性都是默认用public static final修饰的 是常量
接口的成员方法默认都是public abstract修饰的
接口implements的类也可以发生向上转型
接口可以继承接口
抽象类和接口的区别
成员变量
抽象类可以有普通成员变量 静态成员变量 但是接口里的成员只有public static final类型的,即所有的都是不可改变的!!!!
成员方法
抽象类可以有普通成员方法,接口只有抽象成员方法,default方法?
抽象类只能继承一个 接口可以并列实现多个
!!!!!!类描述对象的属性和方法。接口则包含类要实现的方法。
Comparable接口
作用是让自定义的类型可以比较
重写compareTo方法(告诉系统你的比较规则),Comparable<比较的类名>
实现了Comparable接口,并且重写了compareTo方法后,类就能纳入Arrays.sort()的比较范围
import java.util.Arrays;
class Child implements Comparable<Child> {
int age;
String name;
public Child(int age, String name) {
this.age = age;
this.name = name;
}
@Override
public String toString() {
return "Child{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
@Override
public int compareTo(Child c) {
return c.age- this.age;
}
}
public class Interface {
public static void main(String[] args) {
Child[] childs = new Child[3];
childs[0] = new Child(20,"Matty");
childs[1] = new Child(19,"Lyh");
childs[2] = new Child(21,"Lisa");
System.out.println(Arrays.toString(childs));
Arrays.sort(childs);
System.out.println(Arrays.toString(childs));
}
}
Comparator接口
重写compare方法
import java.util.Arrays;
import java.util.Comparator;
class Child {
int age;
String name;
public Child(int age, String name) {
this.age = age;
this.name = name;
}
@Override
public String toString() {
return "Child{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
class AgeCmp implements Comparator<Child> {
@Override
public int compare(Child o1, Child o2) {
return (int)(o1.age - o2.age);
}
}
class StringCmp implements Comparator <Child> {
@Override
public int compare(Child o1, Child o2) {
return o1.name.length() - o2.name.length();
}
}
public class Interface {
public static void main(String[] args) {
Child[] childs = new Child[3];
childs[0] = new Child(20,"Matty");
childs[1] = new Child(19,"Lyh");
childs[2] = new Child(21,"Lisa");
System.out.println(Arrays.toString(childs));
AgeCmp ac = new AgeCmp();
Arrays.sort(childs,ac);
System.out.println(Arrays.toString(childs));
}
}
可以看出Arrays.sort()方法有很多功能强大的重载,这里就是将参数设置为类数组(Object[])+比较方式(Comparator),就可以按照自己设定的比较方式来对类数组进行排序,真的牛逼。
Cloneable接口
通过重写clone方法,产生一个新对象(内容是副本,即浅拷贝),然后返回一个指向该拷贝出来的副本对象的Object引用。
public class Clone implements Cloneable {//Clone类实现了Cloneable接口使得Clone可以被克隆
int age;
@Override
protected Object clone() throws CloneNotSupportedException{
return super.clone();
}
public Clone(int age) {
this.age = age;
}
}
class Tesla {
public static void main(String[] args) throws CloneNotSupportedException {
Clone cl = new Clone(20);
Clone ll = (Clone) cl.clone();
System.out.println(cl.age); //输出20
System.out.println(ll.age); //输出20
ll.age ++;
System.out.println(ll.age); //输出21
System.out.println(cl.age); //输出20
}
}
浅拷贝
简单的赋值
深拷贝
拷贝了对应关系