JDK1.7以及以前:
在JDK7及之前的版本对接口的定义:
1、使用 interface 关键字定义接口
2、接口中没有变量,都是常量,“变量”都默认由 public static final 修饰的,所以没有变量,都是常量!
3、接口中的方法都是抽象方法(针对于1.7及1.7之前),所有方法都默认是由 public abstract 修饰的
4、接口中的 所有方法 都没有方法体,因为都是抽象方法。
5、接口没有构造方法,因为构造方法用于创建对象。
6、实现接口的类必须重写接口中的所有抽象方法,需要提供接口中所有抽象方法的具体实现内容,除非是抽象类,因为抽象类中可以有抽象方法。
// 1、创建接口
interface MyInterface {
// 2、定义变量,但实际上默认是个常量
int a = 1;// 默认由public static final 修饰
public static final int a2 = 2;
// 3、定义方法,但实际上默认是个抽象方法
void method();
}
// 4、创建接口的实现类,
class MyInterfaceImpl implements MyInterface {
// 5、需要重写接口中的所有抽象方法,否则会报错
// The type MyInterfaceImpl must implement the inherited abstract method MyInterface.method()
// 6、重写接口的抽象方法
@Override
public void method() {
System.out.println("MyInterfaceImpl.method()");
}
}
public class InterfaceTest {
public static void main(String[] args) {
// 7、使用多态的方式创建对象
MyInterface mi = new MyInterfaceImpl();
// 8、接口中都是常量,常量的值不可以修改
// The final field MyInterface.a cannot be assigned
// mi.a = 1;
// 9、调用接口中的方法
mi.method();// MyInterfaceImpl.method()
// 10、输出接口中的常量
System.out.println(mi.a);// 1
System.out.println(mi.a2);// 2
}
}
从JDK8开始,接口中可以声明 静态方法 和 默认方法,允许有方法体的方法。
也就是说,从JDK8开始,接口中的方法都是抽象方法这句话就不成立了,从JDK8开始允许有普通方法(有方法体的方法),但是需要被static或default修饰,注意接口里的default不是权限修饰符,在接口里是一个特殊的用法,所以权限修饰符的public才可以和接口里的default连用!
// 1、创建接口 interface MyInterface { // 2、定义变量,但实际上默认是个常量 int a = 1;// 默认由public static final 修饰 public static final int a2 = 2; // 3、定义方法,但实际上默认是个抽象方法 void method(); // 11、从JDK1.8开始,允许接口中定义静态方法和默认方法 // 12、定义普通方法 public default void method2() { System.out.println("MyInterface.method2()"); } // 13、定义静态方法,可以直接通过类名来调用 public static void method3() { System.out.println("MyInterface.method3()"); } // 14、接口里的方法可以互相调用,但不能双向调用,否则会造成类似死循环的效果。最终导致栈溢出错误StackOverflowError public default void method4() { System.out.println("MyInterface.method4()"); method2(); } }
从JDK9开始,增加了私有静态方法的声明
// 1、创建接口 interface MyInterface { // 2、定义变量,但实际上默认是个常量 int a = 1;// 默认由public static final 修饰 public static final int a2 = 2; // 3、定义方法,但实际上默认是个抽象方法 void method(); // 11、从JDK1.8开始,允许接口中定义静态方法和默认方法 // 12、定义普通方法 public default void method2() { System.out.println("MyInterface.method2()"); } // 13、定义静态方法,可以直接通过类名来调用 public static void method3() { System.out.println("MyInterface.method3()"); } // 14、接口里的方法可以互相调用,但不能双向调用,否则会造成类似死循环的效果。最终导致栈溢出错误StackOverflowError public default void method4() { System.out.println("MyInterface.method4()"); method2(); } // 15、私有静态方法,只能在JDK9及以上版本使用 // private static void method5() { // // } }