publicclassSimpleInterfaceImplimplementsSimpleInterface{ @Override publicvoiddoSomeWork(){ System.out.println("Do Some Work implementation in the class"); }
publicstaticvoidmain(String[] args){ SimpleInterfaceImpl simpObj = new SimpleInterfaceImpl(); simpObj.doSomeWork(); } }
Class 'SimpleInterfaceImpl' must either be declared abstract or implement abstract method 'doSomeOtherWork()' in 'SimpleInterface'
여기서 편하게 추가 할수있는 방법은
1 2 3 4 5 6 7 8 9 10 11
package com.github.sejoung.codetest.lamdas;
publicinterfaceSimpleInterface{ publicvoiddoSomeWork(); defaultpublicvoiddoSomeOtherWork(){ System.out.println("DoSomeOtherWork implementation in the interface"); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
package com.github.sejoung.codetest.lamdas;
publicclassSimpleInterfaceImplimplementsSimpleInterface{ @Override publicvoiddoSomeWork(){ System.out.println("Do Some Work implementation in the class"); }
publicstaticvoidmain(String[] args){ SimpleInterfaceImpl simpObj = new SimpleInterfaceImpl(); simpObj.doSomeWork(); simpObj.doSomeOtherWork();
} }
실행결과
1 2 3 4 5 6
Do Some Work implementation in the class DoSomeOtherWork implementation in the interface
Process finished with exit code 0
그럼 이런 경우에는 한번 보자
1 2 3 4 5 6 7 8 9 10 11
package com.github.sejoung.codetest.lamdas;
publicinterfaceInterfaceWithDefaultMethod{ publicvoidsomeMethod(); defaultpublicvoidsomeOtherMethod(){ System.out.println("Default method implementation in the interface"); } }
1 2 3 4 5 6 7 8 9 10
package com.github.sejoung.codetest.lamdas;
publicinterfaceInterfaceWithAnotherDefMethod{ defaultpublicvoidsomeOtherMethod(){ System.out.println("Default method implementation in the interface"); } }
D:\repo\codeTestJDK8\src\main\java\com\github\sejoung\codetest\lamdas\DefaultMethodSample.java Error:(4, 9) java: cannot find symbol symbol: class InterfaceWithDefaultMethod Error:(4, 37) java: cannot find symbol symbol: class InterfaceWithAnotherDefMethod
같은 이름에 동일한 디폴트 메소드가 있을때는 에러메시지를 나타내어 준다
위에 처럼 디폴트 메소드를 사용하면 기존 인터페이스를 해치지 않고 확장 할수 있는 방법이 있다.