Friday 15 May 2015

Default Methods for Interfaces in Java 8

Interfaces always contained only method declaration and there was no way of defining method definition in the interfaces because java did not allow multiple inheritance of classes. Java only allowed multiple inheritance of interfaces. Since Java 8 it is now possible to add method definitions in interfaces.

Java 8 has a additional feature called Default Methods. Now using this method we can add method definitions into interfaces.
Below I am writing example for better understand.

In below Math interface we added a method multiply with method definitions.

    public interface Math {
   
        int add(int a, int b);
   
        default int multiply(int a, int b) {
            return a * b;
        }
    }
    class Sam implements Math {
   
    }
    public class Main {
        public static void main(String [] args) {
        Sam sam = new Sam();
        //calling multiply method calls the method
        //defined in interface
        System.out.println(sam.multiply(25,25));
      }
    }


Read More>> http://findnerd.com/list/view/Default-Methods-for-Interfaces-in-Java-8/2678/

You can find such more Blogs at http://findnerd.com/NerdDigest/

No comments:

Post a Comment