Is it Possible to add static or private methods in Java interface?

Can you add a static or private method in an interface in Java? or is it possible to add a private or static method in Java interface? or can you add a non-abstract method on an interface in Java? are a couple of popular Java interview questions which often pop up during telephonic interviews. 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 the 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.

For long, many Java programmers, particularly beginners and junior developers feel that there is no real use of an interface, well that's completely wrong, given how the interface allows you to write generic, decoupled code, most of those sentiments come from no implementation on the interface.

Things changed for the 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 that works along with interfaces like the Collections for Collection interface, Paths for Path interface, and so on.

Now that, the interface supports 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 The Complete Java Masterclass course on Udemy.





Adding static, private, and default methods on an interface in Java

As I said, from Java 8 it's possible to add both static and default methods on the interface and from Java 9 onwards you can also add private methods in an interface. 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 that 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 interfaces 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 the implementation class, which is great to provide flexibility. You can further join a course like Karpado's Beginner to Advanced Java course to learn these concepts in more detail. For Javarevisited readers, he is offering a first-month subscription for just $1, which is almost like free.

Is it Possible to add static or private methods in Java interface?


2. Static methods

Similar to default methods, you can also add static methods on an interface from JDK 8 onwards, and the 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 to the Java developer's 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 them 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 the 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.

can you add 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.


Related Java 8 Tutorials
If you are interested in learning more about the new features of Java 8 and Java in general, here are my earlier articles covering some of the important concepts of Java 8
  • 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)
  • Top 10 Courses to learn Java for Beginners (courses)
  • How to convert List to Map in Java 8 (solution)
  • Top 5 Courses to become a full-stack Java developer (courses)
  • 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 Java interview question and my explanation then please share it 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, to even Java 15 and 16 then you can also check out this list of free Java courses which I try to update as much as possible. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.