关注: Java提升营 ,最新文章第一时间送达, 10T 免费学习资料 随时领取!!!
在Java 8之前,接口只能定义 抽象方法 。这些方法的实现必须在单独的类中提供。因此,如果要在接口中添加新方法,则必须在实现接口的类中提供其实现代码。为了克服此问题,Java 8引入了 默认方法 的概念,允许接口定义具有实现体的方法,而不会影响实现接口的类。
// 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表达式 ,而无需在实现类中实现这些方法。
接口也可以定义静态方法,类似于 类的静态方法 。
// 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();
}
}
复制代码
输出:
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 复制代码