Showing posts with label Interface. Show all posts

Functional Interface in Java 8

Functional Interface Java 8

In my previous article I explained Difference between Abstract class and Interface in Java. It gives you insight on interface in Java. And Now...

What is @FunctionInterface?
In Simple Term...
Any Interface annotated with @FunctionalInterface, instructs compiler to check that, this Interface should have only one abstract method declared in it.

Characteristics of Functional Interface.
- You can have only one abstract method in Functional Interface.
- You can have default methods and static methods in Functional Interface because they are not abstract.
- You can have public methods of java.lang.Object class in Functional Interface because these method won't count towards Functional Interface's abstract method.

Source Code
/**
 * Any media that is <code>Playable</code> in mobile should implement this interface.
 */
@FunctionalInterface
public interface Playable {

    public void play(String file);

    /* public method of java.lang.Object class */
    @Override
    public boolean equals(Object obj);

    /* public method of java.lang.Object class */
    @Override
    public String toString();

    /* static method to get default player */
    static String defaultPlayer() {
        return "Google Play";
    }

    /* default method to identify file type */    
    default String fileType(String strFilename) {
        if (strFilename == null || strFilename.isEmpty()) {
            return "Provide valid filename";
        }

        if (strFilename.endsWith(".mp3")) {
            return "Audio File";
        } else if (strFilename.endsWith(".mp4")) {
            return "Video File";
        } else {
            return "File not supported";
        }
    }
}

Source Code(Using in Lambda Expression)
public class Motorola {

   public static void main(String[] args) {
      /* Implementing Playable interface using Lambda Expression */
      Playable playable = (String file) -> { System.out.println("Playing Music: " + file); };

      /* Call play */
      playable.play("Pitbull - Give Me Everything ft. Ne-Yo, Afrojack, Nayer.mp4");

      /* Using Interface as parameter in method */
      MusicPlayer((file) -> { System.out.println("Playing Music: " + file); }, "Pitbull - International Love ft Chris Brown.mp4");
   }

   /* Method using Playable interface to play music file */
   public static void MusicPlayer(Playable playable, String file) {
      playable.play(file);
   }
}

Output
Playing Music: Pitbull - Give Me Everything ft. Ne-Yo, Afrojack, Nayer.mp4
Playing Music: Pitbull - International Love ft Chris Brown.mp4

Myth about @FunctionInterface and Lambda Expression
Many developers think if we want to use any Interface in Lambda Expression then it must be Functional Interface. Its completely wrong!

You can use any Interface in Lambda expression that has only one abstract method in it, even if you not annotated Interface with @FunctionalInterface.

But if you are planning to use your Interface as Lambda Expression then annotated your Interface with @FunctionalInterface because compiler will check that this Interface should have only one abstract method at compile time. And also when other developer see that this is functional interface so they won't add new abstract method in it.

Java 8
default and static method in Java Interface

default and static method in Java Interface


In my previous article I explained Difference between Abstract class and Interface in Java. It gives you insight on interface in Java. Now Java designer introduced default and static methods in interface with Java 8. Now you can provide default implementation in Interface.

Why default and static method introduced?
Java designer has to add new methods to existing Java interfaces. For example if Java designer add new method in Iterable interface and you are implementing Iterable interface in one of your class then you've to override that method in your class and if you don't override that method then it'll break your code Java 8 environment.

Considering this one single change in existing Java interface would stop billions of program so they introduced default and static methods in Interface.


Source code(Mobile Interface)
import java.util.TimeZone;

public interface Mobile {

    void voiceCall();

    void sms();

    /* Java 8: static method */
    static TimeZone getTimeZone() {
        return TimeZone.getDefault();
    }
    /* Java 8: default method */
    

    default String deviceLocator(boolean enabled) {
        if (enabled) {
            return "New York";
        } else {
            return "Siberia";
        }
    }
}

Source code(Using Interface)
import java.util.TimeZone;

public class Motorola implements Mobile {

    @Override
    public void voiceCall() {
        System.out.println("voice call");
    }

    @Override
    public void sms() {
        System.out.println("sms");
    }

    public static void main(String[] args) {
        Mobile mobile = new Motorola();

        /* Call voiceCall method */
        mobile.voiceCall();

        /* Call sms method */
        mobile.sms();

        /* Call default method deviceLocator */
        System.out.println(mobile.deviceLocator(true));

        /* Call static method getTimeZone */
        System.out.println(Mobile.getTimeZone().getDisplayName());
    }
}
As you can see its not compulsory to implement deviceLocator and getTimeZone methods in class Motorola.

default method
- Its not compulsory to implement.
- You can @Override default method.

static method
- You can consider static method like utility method and also its not compulsory to implement.
- You can't @Override static method.


Two interface with same default method name
What will be the behavior of class when you have two interface with same default method name implemented by one class? Lets understand it with example.

Source code(GPS Interface)
public interface GPS {

    /* Java 8: default method */
    default String deviceLocator(boolean enabled) {
        if (enabled) {
            return "China";
        } else {
            return "Siberia";
        }
    }
}

Source code(Using Mobile and GPS Interface)
When you implement two interface(Mobile, GPS) in class Motorola which contains same method name then its compulsory for you to @Override default method deviceLocator.
public class Motorola implements Mobile, GPS{
 @Override
    public String deviceLocator(boolean enabled) {
        //GPS.super.deviceLocator(enabled); //Calling specific default method of interface
        return "India";
    }
}

Java 8
Functional Interface in Java 8

Difference between Abstract class and Interface in Java


One of the popular question asked in every single Java interview. People always gets confuse for giving the answer as they don't have fundamental clearance about the topic. If you explain difference with example then interviewer thinks that you have concept clear in your mind. Lets first understand with example and afterword we'll check other characteristics.

Example
Consider a real world object simple mobile phone.
Interface: Each mobile must provide Calling and SMS facility so we can create Interface that has methods Calling, SMS, etc... So if any class Implements MobileInterface then it has to write implementation part of all method written MobileInterface. In our example its Calling ans SMS. Check following source code for better understanding.

Abstract Class: Now What other you can think of that mobile, it may have Mp3 Player, GPS, Camera, etc... but its not compulsory for mobile to have all this feature so we can create an Abstract class that has methods like Mp3Player, GPS, Camera, etc... Its not compulsory to implement all methods of SmartPhoneAbstractClass Abstract class. Check following source code for better understanding.

MobileInterface Source Code
public interface MobileInterface {
    /* Each mobile must have calling facility */
    public void call();
    /* Each mobile must have sms facility */
    public void sms();
}

SmartPhoneAbstractClass Source Code
public abstract class SmartPhoneAbstractClass {
   
    /* Its not compulsory to have MP3 Player in each mobile */
    public void mp3Player(){
        System.out.println("Can have implementation");
    }
    
    /* Its not compulsory to have GPS in each mobile */
    public void GPS(){
        System.out.println("Can have implementation");
    }
}

Main Source Code
public class Main extends SmartPhoneAbstractClass implements MobileInterface{

    /* Mobile must provide calling service */
    @Override
    public void call() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /* Mobile must provide SMS service */
    @Override
    public void sms() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /* Simple mobile has MP3 Player */
    @Override
    public void mp3Player() {
        super.mp3Player();
    }
}

Now you have clear idea about between Interface and Abstract Class. Lets check other characteristics Interface and Abstract Class.

  • Interface doesn't contain implementation part(only declaration) where Abstract class has implementation part.
  • implements keyword is used to implement an Interface where extends keyword is used to extend an Abstract class.
  • You can implement multiple Interface where you can extend only one Abstract class.
  • Variable declared in Interface are by default final where Abstract class can have non final variables.
  • Members of Interface are by default public where Abstract class can have private, protected members.
  • Interface can't have main method where Abstract class can have main method.
  • Interface can't have default constructor where Abstract class can have default constructor.
  • Interface is looks like Java class but its different type of Java file. 
  • You can't create instance of Abstract class. 

Java 8
Functional Interface in Java 8
default and static method in Java Interface