java 1.8中,现在接口也可以定义实现了的方法了。用default定义方法就可以了。具体的例子可以看下面的代码:
public class Test {
public static void main(String[] args) {
Animal bird = new Bird();
bird.breathe();
bird.move();
}
public interface Animal {
default void breathe() {
System.out.println("All animals need to breathe");
}
void move();
}
public static class Bird implements Animal{
@Override
public void move() {
System.out.println("Bird can fly");
}
}
}
输出如下:
All animals need to breathe
Bird can fly
值得注意的一点是,这个default的方法,还可以被子类复写,代码如下:
public class Test2 {
public static void main(String[] args) {
Animal bird = new Bird();
bird.breathe();
bird.move();
}
public interface Animal {
default void breathe() {
System.out.println("All animals need to breathe");
}
void move();
}
public static class Bird implements Animal{
@Override
public void breathe(){
System.out.println("Bird breathe");
}
@Override
public void move() {
System.out.println("Bird can fly");
}
}
}
子类Bird复写了Animal的move方法,结果如下所示:
Bird breathe
Bird can fly
谈一下自己的一些认识,之前1.8以前的接口,如果我们需要修改一个接口的方法的话,那么我们需要修改所有实现了这个接口的类的方法,现在1.8可以解决这个问题了。