Java 8 code KATAs I – Interface with default methods Example

In this series of posts, I will be posting simple java 8 code katas.

Part I – Interface with default methods
Part II – Interface with static methods
Part III – Functional Interfaces & Lambda Expressions
Part IV – Method References
Part V – java.util.function package
Part VI – Streams

First up would be interface with default methods.

Java 8 allows interface to have default implementations.

See the example below:

InterfaceWithDefaultMethodsMain.java


package com.idodevjobs;

public class InterfaceWithDefaultMethodsMain implements InterfaceWithDefaultMethods {

    public static void main (String[] args) {
        System.out.println(new InterfaceWithDefaultMethodsMain().sayHello("test"));
    }
}

interface InterfaceWithDefaultMethods {
    default String sayHello(String message) {
        return "hello " + message;
    }
}


In this example sayHello is a default method in InterfaceWithDefaultMethods interface. Though the concrete class InterfaceWithDefaultMethodsMain implementing InterfaceWithDefaultMethods interface doesn’t override sayHello method, it compiles fine as its a default method. An interface can contain any number of default methods.

Advertisements
This entry was posted in java and tagged . Bookmark the permalink.

5 Responses to Java 8 code KATAs I – Interface with default methods Example

  1. Pingback: Java 8 code KATAs IV – Method References Example | iDoDevJobs

  2. Pingback: Java 8 code KATAs III – FunctionalInterface & Lambda Expressions Example | iDoDevJobs

  3. Pingback: Java 8 code KATAs II – Interface with static methods Example | iDoDevJobs

  4. Pingback: Java 8 code KATAs V – java.util.function Example | iDoDevJobs

  5. Pingback: Java 8 code KATAs VI – Streams | iDoDevJobs

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s