关注:Java提高营,最新文章第一时间送达,10T 免费学习资料随时领取!!!java
在Java 8以前,接口只能定义抽象方法。这些方法的实现必须在单独的类中提供。所以,若是要在接口中添加新方法,则必须在实现接口的类中提供其实现代码。为了克服此问题,Java 8引入了默认方法的概念,容许接口定义具备实现体的方法,而不会影响实现接口的类。bash
// A simple program to Test Interface default
// methods in java
interface TestInterface {
// abstract method
public void square(int a);
// default method
default void show() {
System.out.println("Default Method Executed");
}
}
class TestClass implements TestInterface {
// implementation of square abstract method
public void square(int a) {
System.out.println(a*a);
}
public static void main(String args[]) {
TestClass d = new TestClass();
d.square(4);
// default method executed
d.show();
}
}
复制代码
输出:学习
16
Default Method Executed
复制代码
引入默认方法能够提供向后兼容性,以便现有接口能够使用lambda表达式,而无需在实现类中实现这些方法。spa
接口也能够定义静态方法,相似于类的静态方法。code
// A simple Java program to TestClassnstrate static
// methods in java
interface TestInterface {
// abstract method
public void square (int a);
// static method
static void show() {
System.out.println("Static Method Executed");
}
}
class TestClass implements TestInterface {
// Implementation of square abstract method
public void square (int a) {
System.out.println(a*a);
}
public static void main(String args[]) {
TestClass d = new TestClass();
d.square(4);
// Static method executed
TestInterface.show();
}
}
复制代码
输出:blog
16
Static Method Executed
复制代码
若是一个类实现了多个接口且这些接口中包含了同样的方法签名,则实现类须要显式的指定要使用的默认方法,或者应重写默认方法。继承
// A simple Java program to demonstrate multiple
// inheritance through default methods.
interface TestInterface1 {
// default method
default void show() {
System.out.println("Default TestInterface1");
}
}
interface TestInterface2 {
// Default method
default void show() {
System.out.println("Default TestInterface2");
}
}
// Implementation class code
class TestClass implements TestInterface1, TestInterface2 {
// Overriding default show method
public void show() {
// use super keyword to call the show
// method of TestInterface1 interface
TestInterface1.super.show();
// use super keyword to call the show
// method of TestInterface2 interface
TestInterface2.super.show();
}
public static void main(String args[]) {
TestClass d = new TestClass();
d.show();
}
}
复制代码
输出:接口
Default TestInterface1
Default TestInterface2
复制代码