Java8新增了默认方法和静态方法;
对于已经发布的版本,不影响已有的实现情况下可以增加静态方法和默认方法
1)静态方法可以直接调用,不能被重写
2)默认方法需要通过实现类,重写后实例化后调用
/**
* 接口可以有多个默认方法和静态方法
*/
public interface Java8Interface1 {
//常量
String constant = "java8";
//抽象方法
void doSomething();
//默认方法
default void defaultMethod1() {
System.out.println("Java8Interface1's default method 1 is running...");
}
//默认方法可以有多个
default void defaultMethod2() {
System.out.println("Java8Interface1's default method 2 is running...");
}
//静态方法
static void staticMethod1() {
System.out.println("Java8Interface1's static method 1 is running...");
}
//静态方法也可以有多个
static void staticMethod2() {
System.out.println("Java8Interface1's static method 2 is running...");
}
}
/**
* 接口可以有多个默认方法和静态方法
*/
public interface Java8Interface2 {
//常量
String constant = "java8";
//抽象方法
void doSomething();
//默认方法
default void defaultMethod1() {
System.out.println("Java8Interface2's default method 1 is running...");
}
//默认方法可以有多个
default void defaultMethod2() {
System.out.println("Java8Interface2's default method 2 is running...");
}
//静态方法
static void staticMethod1() {
System.out.println("Java8Interface2's static method 1 is running...");
}
//静态方法也可以有多个
static void staticMethod2() {
System.out.println("Java8Interface2's static method 2 is running...");
}
}
//静态方法不能重写
public class Java8InterfaceImpl implements Java8Interface1,Java8Interface2{
@Override
public void doSomething() {
}
@Override
public void defaultMethod1() {
Java8Interface1.super.defaultMethod1();
Java8Interface2.super.defaultMethod1();
}
@Override
public void defaultMethod2() {
Java8Interface1.super.defaultMethod2();
Java8Interface2.super.defaultMethod2();
}
}
public class Test{
public static void main(String[] args) {
//默认方法 和 抽象方法需实现类实例化后调用
Java8Interface1 java8Interface = new Java8InterfaceImpl();
//抽象方法重写后调用
java8Interface.doSomething();
//默认方法重写后调用
java8Interface.defaultMethod1();
java8Interface.defaultMethod2();
//静态方法直接调用
Java8Interface1.staticMethod1();
Java8Interface2.staticMethod1();
}
}