{{announcement.body}}
{{announcement.title}}

The Interface of Java and the Many Faces of It

DZone 's Guide to

The Interface of Java and the Many Faces of It

Many faces or simply put, an interface’s various parts or it changes its name according to it.

· Java Zone ·
Free Resource

Before beginning the post of Interface of many faces, have you ever heard a phrase, “Man Of Many Faces”? if not, it means a person can be of everything or anything when it comes to portraying something. It can be one thing and a minute after another without losing its strength.

Java’s interface fits perfectly for this title. It is an integral part of java and has become so powerful over the years, that it shifted the way a Java programmer thinks. It has added various ways of doing things in Java. Depending on the number of methods only, an interface’s definition as well as the object creating process changes.

Usual Interface

By definition, it is a template for classes through which you tell classes what you need to do and not, how to. These basically contain abstract functions or methods which, when implemented, need to be overridden. 

Java
 




x
23


 
1
//usual interface
2
 
          
3
interface NormalInterface {
4
 
          
5
    int overrideThisFunction();
6
 
          
7
}
8
 
          
9
 
          
10
 
          
11
class ImplementNormalInterface implements NormalInterface {
12
 
          
13
    @Override
14
 
          
15
    public int overrideThisFunction() {
16
 
          
17
        //Do something
18
 
          
19
        return 0;
20
 
          
21
    }
22
 
          
23
}


Default Function

Now, as I said, It is a template and tells you what to do and not how to. Well, sometimes you need to tell how to do things? Don’t you? A typical scenario would be is when an interface is already published or it is being used in a project far away and you need to add one more function to it. Now if you add one more abstract function to it then boom, now classes can’t be compiled since they need to override this new function. If we use the default function, it lets you define default behavior for the function in case classes can’t override them. However, you can override them if you want to.

Look at newly added functions on  Collection classes such as stream()parallelStream() ,  spliterator()  and many more. It provided you the functionality without actually implemented in the classes.

Java
 




xxxxxxxxxx
1
45


 
1
interface WithDefaultFunction {
2
 
          
3
    int overrideThisFunction();
4
 
          
5
    default int noNeedToOverride(){
6
 
          
7
        return 1 + 1;
8
 
          
9
    }
10
 
          
11
}
12
 
          
13
 
          
14
 
          
15
class ImplementWithDefaultFunction implements WithDefaultFunction{
16
 
          
17
    @Override
18
 
          
19
    public int overrideThisFunction() {return 0;}
20
 
          
21
}
22
 
          
23
class ImplementWithDefaultFunction2 implements WithDefaultFunction{
24
 
          
25
    @Override
26
 
          
27
    public int overrideThisFunction() {return 0;}
28
 
          
29
    
30
 
          
31
    //There is no need to override
32
 
          
33
    //Just in case you want to change the default behaviour
34
 
          
35
    @Override
36
 
          
37
    public int noNeedToOverride() {
38
 
          
39
        //just changed default behaviour
40
 
          
41
        return 2+2;
42
 
          
43
    }
44
 
          
45
}


Static Function

Static functions in the interface are somewhat different. They have a method body but can’t be overridden.  After all, static in Java means, it remains the same for all the instances of the class.  You can have a static method of the same name and parameters, but it will not override the interface’s function. Static functions are called by interface only and no need to create instances of them.

Java
 




xxxxxxxxxx
1
43


1
interface StaticFunction{
2
 
          
3
    static String getAwesomeWebsite(){
4
 
          
5
        return "CodersTea.com";
6
 
          
7
    }
8
 
          
9
    void overrideThis();
10
 
          
11
}
12
 
          
13
 
          
14
 
          
15
class ImplementStaticFunc implements StaticFunction{
16
 
          
17
    //there is no option of overriding static function
18
 
          
19
    //this is not the overridden function
20
 
          
21
    static String getAwesomeWebsite(){
22
 
          
23
        return "https://www.coderstea.com";
24
 
          
25
    }
26
 
          
27
    
28
 
          
29
    @Override
30
 
          
31
    public void overrideThis() { /*do something*/ }
32
 
          
33
 
          
34
 
          
35
    public static void main(String[] args) {
36
 
          
37
        System.out.println("The best website is :" + StaticFunction.getAwesomeWebsite());
38
 
          
39
        
40
 
          
41
    }
42
 
          
43
}


Functional Interface

You can add above functions in a single interface, it doesn’t matter how many default or static function it has. However, the number of abstract methods (without body) affects the interface. More than one it is a normal interface, but with only one abstract method, it is a Functional Interface. A functional interface must have only one abstract method. Only the functional interfaces can be used by lambdas. You can have multiple default and static methods in a functional interface, no issues. It will be a functional interface as long as abstract method count is one.

In Java 8, adding lambda support on these functional interfaces has given rise to a new approach in Java, and that is Functional Programming. It surely  makes the code less cluttered and with the Stream, it changed the way a Java programmer thinks. 

But keep in mind, Lambda only works with the functional interface, and a functional interface only has one abstract method. Java has an annotation, @java.lang.FunctionalInterface, which at compile-time checks for these conditions for the functional interface, otherwise throws the error. It has to be put on the interface only.

Java
 




xxxxxxxxxx
1
47


 
1
@FunctionalInterface
2
 
          
3
interface FunctionalInterfaceDemo{
4
 
          
5
    void iAmTheOnlyOne();
6
 
          
7
    default void iAmAlsoHereButNotAnAbstractMethod(){}
8
 
          
9
}
10
 
          
11
 
          
12
 
          
13
class ImplementFunctionalInterface implements FunctionalInterfaceDemo{
14
 
          
15
    @Override
16
 
          
17
    public void iAmTheOnlyOne() {
18
 
          
19
        //normal overriding
20
 
          
21
    }
22
 
          
23
 
          
24
 
          
25
    public static void main(String[] args) {
26
 
          
27
        FunctionalInterfaceDemo anonymous = new FunctionalInterfaceDemo() {
28
 
          
29
            @Override
30
 
          
31
            public void iAmTheOnlyOne() {
32
 
          
33
                System.out.println("inside lambda");
34
 
          
35
            }
36
 
          
37
        };
38
 
          
39
        FunctionalInterfaceDemo useLambda = () -> System.out.println("inside lambda");
40
 
          
41
        useLambda.iAmTheOnlyOne();
42
 
          
43
        anonymous.iAmTheOnlyOne();
44
 
          
45
    }
46
 
          
47
}



Java has inbuilt functional interfaces, primarily used in Stream APIs, such as FunctionBiFunctionPredicate and many more which you can learn more about in them in my other post “Be More Functional with Java’s Functional Interfaces“. And to learn more about the Stream API, which I like to call “The Hero Without a Cape”here

Conclusion

So these were the many faces or simply put, an interface’s various parts in general. How a single interface changes its behavior with just a certain number or keyword attached to a method. I hope you liked the post and please do comment if I have missed something. Any help would be appreciated.

You can find the code on GitHub here or the full project here. See you at your next tea time.

Topics:
functional interface, functions, interface, java, java8, tutorial

Published at DZone with permission of Imran Shaikh . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}