Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Default Methods for Interfaces in Java 8

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.03k
    Comment on it

    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));
      }
    }
    

    Advantage of default methods in interfaces :-
    1. Default methods will help in extending interfaces without having the fear of breaking implementation classes.
    2. The differences between interfaces and abstract classes in the bridge down of default methods.
    3. Default methods will avoiding utility classes. i.e All the Collections class method can be provided in the interfaces itself.
    4. Default methods will removing base implementation classes.
    5. One of the major reason to introducing default methods is enhance the Collections API in Java 8 to support lambda expressions.
    6. Default methods are also known as Defender Methods or Virtual extension methods.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: