public interface SimpleInterface {
public void doSomeWork();
}
class SimpleInterfaceImpl implements SimpleInterface{
@Override
public void doSomeWork() {
System.out.println("Do Some Work implementation in the class");
}
public static void main(String[] args) {
SimpleInterfaceImpl simpObj = new SimpleInterfaceImpl();
simpObj.doSomeWork();
}
}
那么,如果我们在SimpleInterface里面添加一个新方法,会怎样呢?
public interface SimpleInterface {
public void doSomeWork();
public void doSomeOtherWork();
}
如果我们尝试编译上面的这段代码,会得到如下结果:
$javac .\SimpleInterface.java
.\SimpleInterface.java:18: error: SimpleInterfaceImpl is not abstract and does not
override abstract method doSomeOtherWork() in SimpleInterface
class SimpleInterfaceImpl implements SimpleInterface{
^
1 error
public interface SimpleInterface {
public void doSomeWork();
//A default method in the interface created using "default" keyword
//使用default关键字创在interface中直接创建一个default方法,该方法包含了具体的实现代码
default public void doSomeOtherWork(){
System.out.println("DoSomeOtherWork implementation in the interface");
}
}
class SimpleInterfaceImpl implements SimpleInterface{
@Override
public void doSomeWork() {
System.out.println("Do Some Work implementation in the class");
}
/*
* Not required to override to provide an implementation
* for doSomeOtherWork.
* 在SimpleInterfaceImpl里,不需要再去实现接口中定义的doSomeOtherWork方法
*/
public static void main(String[] args) {
SimpleInterfaceImpl simpObj = new SimpleInterfaceImpl();
simpObj.doSomeWork();
simpObj.doSomeOtherWork();
}
}
该程序的输出是:
Do Some Work implementation in the class
DoSomeOtherWork implementation in the interface
public interface InterfaceWithDefaultMethod {
public void someMethod();
default public void someOtherMethod(){
System.out.println("Default method implementation in the interface");
}
}
public interface InterfaceWithAnotherDefMethod {
default public void someOtherMethod(){
System.out.println("Default method implementation in the interface");
}
}
然后我们定义一个类,同时实现以上两个接口:
public class DefaultMethodSample implements
InterfaceWithDefaultMethod, InterfaceWithAnotherDefMethod{
@Override
public void someMethod(){
System.out.println("Some method implementation in the class");
}
public static void main(String[] args) {
DefaultMethodSample def1 = new DefaultMethodSample();
def1.someMethod();
def1.someOtherMethod();
}
}