Can you add a non-abstract method on an interface in Java?

Well, prior to Java 8, it wasn't possible to add non-abstract methods in Java but nowadays you can add non-abstract static, default, and private methods in Java interface. The static and default methods were supported as part of interface evolution in Java 8 and you can add private methods on an interface from Java 9 onwards. Since long, many Java programmers feel that there is no real use of an interface, well that's completely wrong, given how interface allows you to write generic, decoupled code, most of those sentiments comes from no implementation on the interface.

Things changed for better in Java 8, which introduced static and default methods on the interface. Now, you can specify some default behavior in the interface itself, which is great and removes several popular idioms like having a class for default implementations like Collection and AbstractCollection, List and AbstractList, etc. The same pattern can be implemented using default methods.

Similarly, we used to have a static utility class which works along with interface like Collections for Collection interface, Paths for Path interface and so on.

Now that, interface support static methods, we don't need these kinds of classes and those static utility methods can be now be directly defined in the interface itself as explained in What's New in Java 8 course on Pluralsight.

Let's learn a little bit more about default, static and private methods on an interface in Java:





1. Default methods

From Java 8 onwards, you can specify the non-abstract method in Java. One of these methods is the default method, a method which is declared using the default keyword. You can use these kinds of methods for providing default behavior.

As part of interface evolution in Java 8, several default methods were added into an existing popular interface like Collection and Map. All the classes which implement these interface can now have access to the methods like a stream() and splitIterator() without implementing those.

In earlier versions of Java, it wasn't possible and adding a new method would have broken all existing implementation classes.

Here is an example of a default method on an interface in Java from java.util.Collection interface:

default Stream<E> stream() {
  return StreamSupport.stream(spliterator(), false);
}

This method returns a Stream from Collection. This means if you have a custom Collection implementation and you are running that class in JDK 8 then also you can get Stream from that, even without compiling it.

Unlike static and private methods on an interface, you can also override default methods on implementation class, which is great to provide flexibility. See The Complete Java MasterClass for more details.



2. Static methods

Similar to default methods, you can also add static methods on an interface from JDK 8 onwards, and Java designer has taken advantage of this to provide more useful methods on existing interfaces.

A good example of a static method on an existing interface is comparingByKey() and comparingByValue() methods which returns a Comparator that compares Map.Entry in the natural order of key and value.

Here is an example of a static method on an interface in Java:

public static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) {
   Objects.requireNonNull(cmp);
   return (Comparator<Map.Entry<K, V>> & Serializable)
          (c1, c2) -> cmp.compare(c1.getKey(), c2.getKey());
 
}
 
 
public static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp) {
   Objects.requireNonNull(cmp);
    return (Comparator<Map.Entry<K, V>> & Serializable)
       (c1, c2) -> cmp.compare(c1.getValue(), c2.getValue());
}

These are the overloaded method to compare Map.Entry object by key using the given Comparator. Similarly, you can use static methods on an interface to provide all the utility methods you used to provide in a companion class like Collections or Paths. If you are interested to learn more about the static method on the interface, Java Fundamentals: The Java Language course on Pluralsight s an excellent resource.

Can you add a non-abstract method on an interface in Java?



3. Private methods

This one is a new addition in Java developers arsenal. From JDK 9 onwards you can now also define private methods on an interface in Java. Because you cannot override private methods, there is very limited use of it but they are excellent for providing helper methods.

For example, if you have an interface CharStream which has a couple of methods to generate a sequence from integer like below:

public static CharStream of(char c1)

public static CharStream of(char c1, char c2)

public static CharStream of(char c1, char c2, char c3)

Then each of these methods can call a helper private method like below:

private static CharStream makeFiniteCharStream(char... characters){

...

}

This allows you to avoid duplicate code and make clever use of variable arguments feature of Java 5. If you are interested in learning other enhancements in Java 9 e.g. static factory methods on Collections, JShell, and Java Module system, etc, I suggest you check  The Complete Java MasterClass on Udemy.

non-abstract method on an interface in Java?


That's all about whether you can specify non-abstract methods on an interface in Java or not. Yes, it is not possible in the earlier version of Java e.g. until JDK 7 but from JDK 8 onwards you can specify non-abstract methods in form of default and static methods on the interface. From JDK 9 onwards, you can even declare private methods on an interface in Java.


Further Learning
The Complete Java MasterClass
The Ultimate Java 8 Tutorial
From Collections to Streams in Java 8 Using Lambda Expressions


Related Java 8 Tutorials
If you are interested in learning more about new features of Java 8 and Java in general, here are my earlier articles covering some of the important concepts of Java 8
  • Java 8 Interview Questions Preparation Course (free)
  • How to sort the map by keys in Java 8? (example)
  • How to use filter() method in Java 8 (tutorial)
  • 5 Books to Learn Java 8 from Scratch (books)
  • What is the default method in Java 8? (example)
  • How to use Stream class in Java 8 (tutorial)
  • How to convert List to Map in Java 8 (solution)
  • How to join String in Java 8 (example)
  • 20 Examples of Date and Time in Java 8 (tutorial)
  • Difference between abstract class and interface in Java 8? (answer)
  • 10 Free Courses for Experienced Java Programmers (courses)
  • How to sort the may by values in Java 8? (example)
  • How to use peek() method in Java 8 (example)
  • How to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • 5 Free Courses to learn Java 8 and 9 (courses)
Thanks for reading this article so far. If you like this article then please share with your friends and colleagues. If you have any questions or feedback then please drop a note.

P.S. - If you are interested in learning more about new features introduced since Java 8 version like in Java 9, Java 10, Java 11, and Java 12, you can also check out this list of free courses.

No comments:

Post a Comment