Functional interface in Java

Function interface in Java

We discussed interfaces and abstract class in earlier, let’s discuss specific type of interface called functional interface. A functional interface is an interface with only one abstract method. This abstract method is implemented by class. Below is example of a functional interface, interface CustomFunctionalInterface has only one abstract method abstractMethod.

@FunctionalInterface
public interface CustomFunctionalInterface {
	public boolean abstractMethod(Integer a);
}

Notice that there is special annotation @FunctionalInterface added in Java 8 to help compile type check, if you add another abstract method in functional interface, it will throw an error.

What happens when another interface inherit functional interface? If there is no other abstract method defined in child interface, it automatically become functional interface. Child interface can have default methods and still be functional.

It’s not that the functional interfaces came in Java 8, they preexisted, example being Runnable interface mentioned above. However there are many functional interfaces like Predicate are introduced in Java 8. By virtue of their ability to pass around functionality(i.e. behavior), functional interfaces primarily enable behavior parameterization.

Functional interface and anonymous class

Anonymous class is a class without a name. Anonymous classes are created and instantiated using functional interfaces. One of the most common example is instantiating Runnable class.

public class AnonymousInnerClassTest {
	public static void main(String[] args) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("A thread created and running");
			}
		}).start();
	}
}

This does not mean that anonymous classes can only be created using functional interface, but it is less clumsy and  more understandable when using one. Notice how anonymous class is created, 

The anonymous class expression consists of the following:

  • The new operator
  • The name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface Runnable.
  • Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.
  • A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not

Let’s see an example where we are using functional interfaces.

Please share if there is something is missing or wrong. If you want to contribute to website, please reach out to us on communications@algorithmsandme.com

Default methods in interface In Java 8

Default methods in interface

Before understanding default methods in interface, first understand what in an interface. An interface is the contract an object exposes to the outside world. An interface is a reference type in Java. It is a collection of abstract methods which are implemented by class.

In plain terms, let’s say you are developing a program which interact with multiple TV sets. These TV sets will have different types of remote operating them. Now, if you implement version of our program for each type of TV and remote available in market, it will be a nightmare.
That’s why we expose an interface or contract which all TV set implementation adhere to and all remotes can use that interface to operate desired functionality.
Here advantage is that no matter what internal implementation of TV is as far as it follows the same interface, remote will work.

	interface TV { 
		public boolean switchOn();
		public boolean switchOff();
		public int changeChannel();
		public int volumeDown();
		public int volumeUp()
	} 

We can implement these methods in any which way we like on different TV sets (objects) without having to change remotes (outside world implementation).

public class SamsungTV implements TV {
	public boolean switchOn() {
		// implementation
	}

	public boolean switchOff() {
		// implementation
	}

	public int volumeDown() {
		// implementation
	}

	public int volumeUp() {
		// implementation
	}
}

As you noticed that interface only contains abstract function and does not give any implementation of any function. However, with Java 8 that has changed. An interface can have default implementation of a function.

	public interface InterfaceExample {
		// to be implemented by class
		void abstractMethod(String str);
	
		default void defaultMethod(String str){
			System.out.println("logging::"+str);
		}
	}

Why was that required? Imagine a case where you defined an interface and whole lot of classes implemented it in whatever way they wanted to. Now, at certain time in your project, you decided to add another method to the interface. It will need update of all classes which implement interface. 
How about a default implementation of new function and classes can implement it if they want different behavior? One of the major reason for introducing default methods in interfaces is to enhance the Collections API in Java 8 to support lambda expressions.

As you know, Java does no allow multiple inheritance, that is to inherit more than one class, because that leads to “diamond problem. However, which interfaces having default implementation, and classes can implement multiple interfaces, “diamond problem” is bound happen. If two interface implement same function which function should be used by class object? 
To solve this problem, it is mandatory to provide implementation of common default methods of interfaces by class else compiler will throw errors.

	public interface InterfaceExample1 {
		// to be implemented by class
		void abstractMethod1(String str);
	
		default void defaultMethod(String str){
			System.out.println("logging::"+str);
		}
	}		
	public interface InterfaceExample2 {
		// to be implemented by class
		void abstractMethod2(String str);
	
		default void defaultMethod(String str){
			System.out.println("logging::"+str);
		}
	}		
public class ExampleClass implements InterfaceExample1, InterfaceExample2 {

	@Override
	public void abstractMethod1() {
	}

	@Override
	public void abstractMethod2(String str) {
	}

	@Override
	public void log(String str){
		System.out.println("MyClass logging::"+str);
	}
}

Default methods in interfaces actually bridges the gap between abstract classes and interfaces in Java. Also, it safeguards again breaking of code in case interfaces are modified. 

Please share if there is something wrong or missing. If you want to contribute to website, please reach out to us on communications@algorithmsandme.com

Abstract class Vs Interface

Difference between abstract class and interface

To understand difference between abstract class and interface, first, we have to understand what is an abstract class and an interface and what are the similarities.

Abstract class in plain terms is a class which contains one more abstract methods. Abstract method has no implementation, just a declaration. Sub-classes of abstract class are responsible for providing implementation of such methods. Example of an abstract class as follows

package Examples;

/**
 * Created by sangar on 22.10.17.
 */
public abstract class AbstractBicycle {
    //member fields
    protected int gears;
    protected int topSpeed;
    protected int serviceCost;

    public int getGears(){
        return this.gears;
    }

    public abstract void service();
}

 

On the other hand, interfaces are like contracts which are honored by every class which implements them. It does not matter how a class implement the contract, as far as it implements it. For example, Television box can have may functionalities like changing channels, volume control, records, selection of source etc. TV manufacturers defined this industry standard interfaces, so that remotes can be build to call these behaviors on TV sets. It does not matter how different models of TV implement these interface, as far as they implement it.

Interface is again just like a class, which contains all abstract methods.  Implementation of those methods is left to class  which implements interface. Interface can contain constants too which are by default final. Example of declaration of an interface be

package Examples;

/**
 * Created by sangar on 22.10.17.
 */
interface IBicycle {

    void changeGear(int newValue);

    void speedUp(int increment);

    void applyBrakes(int decrement);
}

So, what’s the difference between abstract class and interface then? There are very subtle differences as follows

  1. Abstract class is object oriented in nature as it defines hierarchy between classes, on the other hand interfaces are functional in nature as they define what a class has to implement to satisfy this interface.
  2. Methods and fields in abstract class can have individual access specifiers like private, public or protected, where as in interfaces, everything has to be public. Sub-class implementing abstract methods from abstract class can keep visibility same or reduce it, whereas class implementing interface has to keep visibility same which is public.
  3. A sub-class or child can only extend single abstract class, whereas a class can implement multiple interfaces.
  4. By definition, abstract class can have default implementation of some methods, where as interface just has definition of all methods. This is not true from Java 8 default method signatures in interface. Refer here for more details.
  5. Sub-class uses extends to use abstract class where implements to implement an interface.
  6. Abstract classes can have constructors but interfaces can’t have constructors.

Abstract class Vs Interface : When to use what?

Now, when to use what? When to use abstract class and when to go to interfaces.

Consider using abstract classes if any of these statements apply to your situation:

  • You want to share implementation among several closely related classes.
  • You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
  • You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.

Consider using interfaces if any of these statements apply to your situation:

  •  If unrelated classes would implement your interface.
  • Specify the behavior of a particular data type, but not concerned about who  implements its behavior.
  • You want to take advantage of multiple inheritance of type.

Reference : Oracle documentation

In short, abstract class provides is-a kind of relationship between class and concrete sub-classes whereas interface provides has-a capability between unrelated classes.

This post clarifies difference between abstract class and interface and explains when to use what. Hope it helped you!

Please share if there is something wrong or missing. If you want to contribute to website, please reach out to us through contact form or drop a mail to jitsceait@gmail.com.