理解
1.接口是与类同级的。抽象类还属于类。
2.继承是一种is-a的关系(Animal和Dog),而接口是一种has-a的关系(Bird和Flyable)。
接口的特点
1.接口中的基本数据类型都是全局静态常量。
public static final double PI=3.14;
2.接口中的方法都是全局抽象方法(jdk1.7之前),jdk1.8中接口中的方法可以有静态非抽象的方法方法。
public abstract void fly();
static void run(){}
3.在定义方法时,接口可作为形参类型,而实参可以是任意实现该接口的类。(其实也是多态的一种体现)。同样,类实现多态,的类中特有的方法是无法调用的。
public class Plane implements Flyable{
@Override
public void fly() {
System.out.println("I am Plane.I can fly");
}
}
public class Bird implements Flyable{
@Override
public void fly() {
System.out.println("I am a Bird.I can fly");
}
}
public class Test {
public static void Match(Flyable flyable){
flyable.fly();
}
public static void main(String[] args) {
Bird bird=new Bird();
Match(bird);
Flyable plane=new Plane();
Match(plane);
}
}
4.接口也可以继承接口。
public interface Flyable extends HightFly
5.一个类既可以继承父类(使用extends关键字),又可以实现接口(使用implement)关键字。但要注意是先写继承,再写实现。
6.一个类可以实现多个接口。
作用
变相的实现了C++的多继承。有没有C++的不安全性。
应用Comparable接口
public interface Comparable {
int compareTo(Object other);
}
ublic class People implements Comparable {
String name;
int age;
public People(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Object o) {
People other=(People)o;
int result =this.age-other.age;
if(result==0){
return this.name.compareTo(other.name);
}else{
return result;
}
}
}
public class Test {
public static void main(String[] args) {
People people=new People("锅盖",19);
People people1=new People("锅盖1",19);
System.out.println(people.compareTo(people1));
}
}
JDK1.8接口新特征
引入了两个非抽象的方法
1.static修饰的静态非抽象方法
public static void method2(){
System.out.println("Interface method2");
}
特点:
(1)因为是静态的方法,所以可以在main方法中直接调用。并且main也可以直接写在接口中。
(2)必须通过接口名来调用。
(3)不能被重写
2.default修饰的非抽象方法
(1)可以被实行类所继承,也可以被实现类所重写。但重写的时,要把default去掉。
(2)必须通过类名来调用。
作用:
提供default修饰的非静态方法,可以让实现类来继承。即相当于为每个实现类提供了一个默认的方法,并且实现类可以重写该方法。可以减少实现类中的代码。举例:如果有10个接口,
每个接口有20个抽象方法,20个实现类。这样一共就要实现4000个方法。如果提供了非抽象的方法,如果满足实现类的要求,就不用重写了。有1个方法不用重写,就可以少实现200个方法。