Wednesday, June 1, 2016

Java 8 Interface Static and Default Methods

  • Java 8 introduced two new methods in interface they are
    1.default methods
    2.static methods
  • By this interfaces and abstract class are same but still having lot differences like abstract class can have a constructor etc will discuss more before that we need to know about these Java 8 features of interfaces.
  • Defaults methods are also called as defender methods can be implemented inside the interface
  • Like normal class now with java 8 we can declare static methods in side a interface.
  • Lets jump deep into Java 8 default and static methods 

Interface Default Methods in Java 8

  • Before Java 8 in interfaces we can and able to declare only abstract methods only.
  • If we declare a method without abstract that will be treated as abstract by default.
  • As we know all methods in interfaces are by default abstract methods.
  • These methods wont have body means implementations
  • The class which is implementing this interface need to provide body / implementation for this abstract methods.
  • Now with java 8 default methods we can add methods to interface without disturbing existing functionality.
  • So instead of overriding now we can inherit these default methods from interfaces
  • Defaults methods are also  known as defender methods or virtual extension methods
  • Default methods will help us to avoid utility classes.
  • We can define utility methods inside the interface and use it in all classes which is implementing.
  • One of the major reason to introduce this default methods in java 8 is to support lambda expressions in collections API and to enhance.


  1. package com.instanceofjava;
  2. interface Java8Interface{
  3.  
  4. abstract void show();
  5.   
  6. default void display(){
  7.  
  8. System.out.println("default method of interface");
  9.  
  10. }
  11. }


  1. package com.instanceofjava;
  2. class Sample implements Java8Interface {
  3.  
  4. void show(){
  5. System.out.print("overridden method ")
  6.  }
  7. public static void main(String[] args){
  8.   
  9. Sample obj= new Sample();
  10.  
  11. obj.show(); // calling implemented method
  12. obj.display(); // calling inherited method
  13. Java8Interface.display(); calling using interface name
  14.  
  15. }
  16. }

Output:

  1. overridden method
  2. default method of interface
  3. default method of interface

How to call default methods:

  • We can all these default methods by using interface name and also by using object of the class which is implementing.
  • From above example
  • obj.show(); // calling implemented method
  • obj.display(); // calling inherited method
  • Java8Interface.display(); calling using interface name

    Can we override java 8 default method

    • As we discussed above default methods in interfaces are implemented methods with bodies
    • Yes we can override same method in class which is implementing this interface.
    • Lets see one sample program how to override and what happens if we override


    1. package com.instanceofjava;
    2. interface InterfaceWithDefault{
    3.  
    4. default void defMethod(){
    5.  
    6. System.out.println("default method of interface");
    7.  
    8. } 
    9. }


    1. package com.instanceofjava;
    2. class Demo implements InterfaceWithDefault{
    3.  
    4. void defMethod(){
    5.  
    6. System.out.print("overridden method in class Demo ") 
    7.  
    8.  }
    9. public static void main(String[] args){
    10.   
    11. Demo obj= new Demo();
    12.  
    13. obj.defMethod(); // calling overridden method
    14. Java8Interface.defMethod(); calling using interface name : interface defMethod will be called
    15.  
    16. }
    17. }

    Output:


    1. overridden method in class Demo
    2. default method of interface

    What happens if we implement two interfaces having same default methods

    • Now lets see if a class implementing two interfaces which are having same default methods
    • Whatever the implementation in the two interfaces defined if we implementing two interfaces which are having a default method in both then compilation error will come if two methods have same signature. works fine if two methods have same name with different arguments.
    • Check the below example programs to understand more.


    1. package com.instanceofjava;
    2. interface A{
    3.  
    4. default void defMethod(){
    5.  
    6. System.out.println("default method of interface: A");
    7.  
    8. }
    9.  
    10. }


    1. package com.instanceofjava;
    2. interface B{
    3.  
    4. default void defMethod(){
    5.  
    6. System.out.println("default method of interface: B");
    7.  
    8. } 
    9. }

    1. package com.instanceofjava;
    2. class Demo implements A, B{ // compilation error will come
    3.  
    4. public static void main(String[] args){
    5.   
    6. Demo obj= new Demo();
    7.   
    8. }
    9. }

    • If we implement two interfaces which are having same method with same parameters then compilation error will occur.
    • Duplicate default methods named "defMethod" with the parameters () and () are inherited from the types A and B.
    • If we define two methods with different type of parameters then we can work with both interfaces.

    1. package com.instanceofjava;
    2. interface A{
    3.  
    4. default void defMethod(){
    5.  
    6. System.out.println("Default method of interface: A");
    7.  
    8. }
    9.  
    10. }


    1. package com.instanceofjava;
    2. interface B{
    3.  
    4. default void defMethod(String str){
    5.  
    6. System.out.println("Default method of interface: B");
    7. System.out.println(str);
    8.  
    9. }
    10. }

    1. package com.instanceofjava;
    2. class Demo implements A, B{ // compilation error will come
    3.  
    4. public static void main(String[] args){
    5.   
    6. Demo obj= new Demo();
    7. obj.defMethod();
    8. obj.defMethod("Java 8")
    9.  
    10. }
    11. }

    Output:


    1. Default method of interface: A
    2. Default method of interface: B 
    3. Java 8

    Interface Static Methods in Java 8

    • Another Java 8 interface method is static method.
    • Now we can define static methods inside interface but we can not override these static methods.
    • These static method will act as helper methods.
    • These methods are the parts of interface not belongs to implementation class objects.


    1. package com.instanceofjava;
    2. interface StaticInterface{
    3.  
    4. Static void print(String str){
    5.  
    6. System.out.println("Static method of interface:"+str);
    7.  
    8. }
    9. }

    1. package com.instanceofjava;
    2. class Demo implements StaticInterface{
    3.  
    4. public static void main(String[] args){
    5.   
    6.  StaticInterface.print("Java 8")
    7.  
    8. } 
    9. }

    Output:


    1. Static method of interface: Java 8

    Java 8 Features

    1. Default and Static methods in Interface
    2. Lambda Expressions
    3. Optional
    4. Streams
    5. Method References
    6. Data Time API
    7. Nashorn Javascript Engine
    8. Parallel Arrays

    1.Default and Static methods in Interface :

    • Java 8 introduces new features to interfaces.
    • Before java 8 interface having only abstract methods but now java 8 added two more type of methods to interface !.
    • First one is default method. A method which is having a default keyword with method body.
    • Actually interfaces wont have any implemented methods  but now with java 8 default method we can add a method with default implementation by using "default " keyword.
    • The classes which are implementing this interface can use these default method and same time it can override the existing method. But its not mandatory to override.



    1. package com.instanceofjava;
    2. interface Java8InterfaceDemo{
    3.  
    4. abstract void add();
    5.   
    6. default void display(){
    7.  
    8. System.out.println("default method of interface");
    9.  
    10. }
    11.  
    12. }


    • The second new method introduced in java 8 is static method.
    • Yes like in classes now we can define a static methods inside interface by using "static".
    • Basically static methods which are defined in interface are interface level only. if we want to call these static methods which are defined in interfaces we need to use interface name so that we can access these methods.



    1. package com.instanceofjava;
    2. interface Java8InterfaceDemo{
    3.  
    4. abstract void add();
    5.   
    6. default void display(){
    7.  
    8. System.out.println("default method of interface");
    9.  
    10. }
    11.  
    12. public static void show(){
    13.  
    14. System.out.println("static method of interface");
    15.  
    16. }
    17.  
    18. }

    2.Lambda Expressions 

    • One of the most awaited and biggest release in java 8 is lamda expressions.
    • Ability to pass functionality/ behavior  to methods as arguments.
    • Allows us to write a method in the same place we are going to use it.


    1. package com.instanceofjava;
    2. interface JavalamdaExpression{
    3.  
    4. public static void main(String[] args){
    5.  
    6.  Arrays.asList( "j", "a", "v" ,"a","8").forEach( e -> System.out.print( e ) );
    7.  // java8
    8. }
    9.  
    10. }

    3.java.util.Optional:

    • One of the best and cool feature of java 8 is Optional class. Which is a final calls from java.util package.
    • The major repeating statement in every project is checking "NullPointerException". Before using any object we need to check whether it is null or not if its not null then only we need to proceed.
    • Optional is just like a container which holds a value of type <T> or "null". By using isPresent() method of Optional class we can check particular object is null not not.



    1. package com.instanceofjava;
    2. import java.util.Optional:
    3. class Java8OptionalDemo{
    4.  
    5. public static void main(String[] args ){
    6.  
    7.  Optional< String > str = Optional.ofNullable( null );
    8.  System.out.println( "str having value ? " + str.isPresent() ); // output : str having value ? false
    9.  
    10. }
    11. }

    4.Streams:

    • One of the excellent feature from java 8 as java.util.stream.
    • Stream API  introduces real-world functional-style programming into the Java.
    • Provides functional operations on stream of elements such as list , set and map 
    • Supports filtering, mapping and removal of duplicates of elements in collections, are implemented lazily.
    • Now we can get Streams from collections, arrays and bufferedReaders etc.



    1. package com.instanceofjava;
    2. import java.util.Arrays;
    3. class Java8StreamsDemo{
    4.  
    5. public static void main(String[] args ){
    6.  
    7.   Arrays.stream(new int[] {1, 2, 3,4,5})
    8.     .map(n -> 2 * n + 1) 
    9.    .average()
    10.     .ifPresent(System.out::println); // output: 7.0
    11.   
    12. }
    13. }

    5.Method Reference:

    • We can use lambda expressions to create anonymous methods. 
    • Sometimes, however, a lambda expression does nothing but call an existing method. 
      In those cases, it's often clearer to refer to the existing method by name.
    • Using Method references refer to the existing method by name, they are compact, easy-to-read lambda expressions for methods that already have a name


    1. package com.instanceofjava;
    2. import java.util.Arrays;
    3.  
    4. class Java8MethodRef{
    5.  
    6.   public  void show(String str){
    7.  
    8.         System.out.println(str);
    9.  
    10.    }
    11.  
    12. public static void main(String[] args ){
    13.  
    14.    Arrays.asList("a", "b", "c").forEach(new A()::show); // a b c

    15.  
    16. }
    17.  
    18. }

    6.Data Time API  

    • The next cool feature from java 8 is new date time API(jsr 310) added within java.time package.
    • Before java 8 if we want to format dates we use SimpleDateFormatter class in java 8 while declaring date itself it has constructor to pass format of date.
    •  Some of the new classes introduced in java 8 date time are as follows.
    1. LocalTime
    2. LocalDate 
    3. LocalDateTime
    4. OffsetDate
    5. OffsetTime
    6. OffsetDateTime

    1. package com.instanceofjava;
    2. import java.util.Arrays;
    3.  
    4. class Java8DateTimeAPI{
    5.  
    6. public static void main(String[] args ){
    7.          
    8.     LocalDate currentDate = LocalDate.now();
    9.     System.out.println(currentDate);
    10.     
    11.     LocalDate twentyMarch2015 = LocalDate.of(2015, Month.MARCH, 06);
    12.     System.out.println(twentyMarch2015);  //2015-03-06
    13.  
    14.      LocalDate firstApril2015 = LocalDate.of(2015, 4, 1);
    15.      System.out.println(firstApril2015);//2015-04-01
    16.  
    17. } 
    18. }

     7.Nashorn Javascript Engine

    •  Java 8 come with new Nashorn Javascript Engine which is allowing us to develop and run JavaScript applications.



    1. package com.instanceofjava;
    2.  
    3. import javax.script.ScriptEngine;
    4. import javax.script.ScriptEngineManager;
    5. import javax.script.ScriptException;
    6.  
    7. import java.util.Arrays;
    8.  
    9. class Java8JavaScript{
    10.  
    11. public static void main(String[] args ){
    12.          
    13.   ScriptEngineManager manager = new ScriptEngineManager();
    14.   ScriptEngine engine = manager.getEngineByName( "JavaScript" );
    15.   System.out.println( engine.getClass().getName() );
    16.   System.out.println( "output:" + engine.eval( "function show() { return 10; }; show();" ) );
    17.  
    18. } 
    19. }


    1. jdk.nashorn.api.scripting.NashornScriptEngine
    2. output:10

    8.Parallel Array Sorting

    • As of now java 7 we already having Arrays.sort() method to sort objects now java 8 introduced parallel sorting which has more speed than arrays.sort() and follows Fork/Join framework introduced in Java 7 to assign the sorting tasks to multiple threads that are available in the thread pool.
    • Java 8 added parallel sorting functionalities to java.util.Arrays to take advantage of multithread machines 

    1. package com.instanceofjava;
    2. import java.util.Arrays;

    3. class Java8JavaScript{
    4.  
    5. public static void main(String[] args ){
    6.          
    7.          int arr[]={1,4,2,8,5};
    8.          Arrays.parallelSort(arr);
    9.  
    10.          for(int i:arr){  
    11.              System.out.println(i);  
    12.            } 
    13.  
    14. } 
    15. }