2. Defender Methods : Till java 7 , every interface only has - TopicsExpress



          

2. Defender Methods : Till java 7 , every interface only has method declaration and no implementations , and any non abstract class which implements the interface has to implement every method in interface public interface MyInterface { public void doAnyWork(); } class MyInterfaceImpl implements MyInterface { @Override public void doAnyWork(){ System.out.println(Do Any work in the class ); } public static void main (String args[]) MyInterfaceImpl myobject= new MyInterfaceImpl(); myobject.doAnyWork(); } } Now suppose if i add some method doMoreWork() abstract method in MyInterface interface , then , if we try to compile the code , we will get compiler error $javac .\MyInterface.java .\MyInterface.java:18: error: MyInterfaceImpl is not abstract and does not override abstract method doMoreWork() in MyInterface class MyInterfaceImpl implements MyInterface{ ^ 1 error And this limitation makes the situation almost impossible to change the interface or APIs . To overcome this challenge , java 8 introduces default method also known as defender method . public interface MyInterface { public void doAnyWork(); // A default method in the interface created using default keyword default public void doMoreWork(){ System.out.println (Do More Work implementation in the interface ) ; } } class MyInterfaceImpl implements MyInterface { @Override public void doAnyWork(){ System.out.println(Do Any work implementation in the class ); } /* * Not required to override to provide an implementation * for doMoreWork */ public static void main (String args[]) MyInterfaceImpl myobject= new MyInterfaceImpl(); myobject.doAnyWork(); myobject.doMoreWork(); } } And the output of the code will be : Do Any Work implementation in the class Do More Work implementation in the interface
Posted on: Sat, 23 Aug 2014 07:29:26 +0000

Trending Topics



style="margin-left:0px; min-height:30px;"> Too busy to shop this holiday season? Are classes and exams

Recently Viewed Topics




© 2015