Java 8 Default Methods FAQ - Frequently asked Questions and Answers

In last a couple of articles, I have to talk about default methods introduced in JDK 8. First, we have learned what is default method and why it is introduced in Java. Then we have seen the example of how you can use default methods to evolve your interface. After that we have analyzed does Java really support multiple inheritances now in JDK 8 (see here) and how will Java handle the diamond problem that will arise due to default methods. For example, what will happen if a class extend a class and implement an interface and both contain a concrete method with same method signature? Will a diamond problem arise? How will Java handle that and how you can solve it, and the difference between abstract class and interface in Java 8?  Once you went through those articles, you would have a good knowledge of default methods in Java 8.

In order to summarize those articles and revise the key concept, I have created a list of frequently asked question about default methods on Java 8. In this list, you will find them some of them. Though the list is not very exhaustive, it contains some decent questions to check your understanding of default methods of JDK 8 as well as to encourage you to find more about them and fill gaps in your understanding.



Java 8 Default Methods Frequently Asked Questions

Enough of theory, now, it’s time to answer some frequently asked question about Java 8 default methods:


1) Can we make Default method static in Java?

No, You cannot make default method static in Java. If you declare static method and default together, the compiler will complain saying "illegal combination of modifiers: static and default". For example, following code will not compile :

interface Finder{   
    static default void find(){
        System.out.println("default find method");
    }
}

but at the same time, let me tell you another interesting interface improvement coming in Java 8. If you remember correctly, You cannot declare a static method inside interface in Java, but from Java 8 onwards, an interface can contain static methods. See What's New in Java 8 to learn more about new features of Java 8.

A couple of Java classes are enhanced to contain static utility methods, which otherwise was declared in a separate static utility class. For example, a static method called naturalOrder() was added to java.util.Comparator interface, as shown below :


public static <T extends Comparable<? super T>> Comparator<T> naturalOrder() {
    return (Comparator<T>)Comparators.NaturalOrderComparator.INSTANCE;
}

There are a couple of more e.g. sort() method is added into java.util.List and there is a reversed() method added on Comparator interface. In short, a lot of static and default methods are added into existing interface to make them better. I suggest you read a good Java  8 book e.g. Java 8 in Action to learn more about those methods.



2) Can an interface contain more than one Default methods?

Yes, any Java interface can contain more than one default methods. But, I have yet to find reasons for adding multiple default methods on an interface, because default implies to one behavior, not multiple behaviors. Anyway, Java 8 compiler is happy to let you declare more than one default methods, as shown below :

interface Some{   
    default void first(){
        System.out.println("first default method");
    }
   
    default void second(){
        System.out.println("Second default method on Java 8 interface");
    }
   
    default void third(){
        System.out.println("Third default method");
    }
}


3) Can default method override equals(), hashCode() or toString() from Object class?

No, default method cannot override any method from java.lang.Object, trying to override toString(), equals() or hashCode() as default method in an interface on Java 8, will throw compile time error as "default method toString in interface parser overrides a member of java.lang.Object, as shown below :
interface Parser{   
  
    @Override
    default String toString(){
        return "";
    }
}
Compile time error : "default method toString in interface
 parser overrides a member of java.lang.Object"

This may look odd to many programmers, given some interface actually defines their equals behavior in documentation e.g. List.

So why default methods are prevented from overriding equals(), hashCode() or any other method from Object class? Brian Goetz answered this question on project lambda mailing list in detail, one of them is following, which gives you enough idea behind this reasoning.

"It would become more difficult to reason about when a default method is invoked. Right now it's simple: if a class implements a method, that always wins over a default implementation.

Since all instances of interfaces are Objects, all instances of interfaces have non-default implementations of equals/hashCode/toString already. Therefore, a default version of these on an interface is always useless, and it may as well not compile.". You can also read Java 8 in Action to learn more about this concept.



4) Can we declare Default methods inside a class in Java?

No, you can't, but just think about why do you need default methods for Java classes, unlike implementation of an interface, there is no requirement for all subclasses to implement a new method added inside a Java class. A class can evolve without requiring a change in its subclasses.

Of course, when you add a new abstract method inside an abstract class, then it will break your subclasses, but you don't need default method to save there, a normal method will do the job.

5) Can default method be abstract in Java?

Another question, which can be answered by just thinking about it. It’s similar to, can a class be final and abstract at the same time or can we declare a Java method final and abstract? Default methods are invented, just to provide a concrete method inside interface. Since adding a new method inside interface, break all its implementation, because they are inherently abstract, requiring all clients to implement that.


That's all about some of the frequently asked questions about default methods in Java 8. If you have any other question about default and static methods in Java 8 and their application on interface then feel free to drop a comment. I'll try to find an answer for you.

Further Reading
What's New in Java 8
Java SE 8 for Really Impatient
From Collections to Streams in Java 8 Using Lambda Expressions
Streams, Collectors, and Optionals for Data Processing in Java 8


Related Java 8 Tutorials
If you are interested in learning more about new features of Java 8, here are my earlier articles covering some of the important concepts of Java 8:

  • 5 Books to Learn Java 8 from Scratch (books)
  • How to join String in Java 8 (example)
  • How to convert List to Map in Java 8 (solution)
  • How to sort the map by keys in Java 8? (example)
  • How to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • 10 examples of Optionals in Java 8? (example)
  • How to use forEach() method in Java 8 (example)
  • How to use filter() method in Java 8 (tutorial)
  • How to use peek() method in Java 8 (example)
  • How to use Stream class in Java 8 (tutorial)
  • How to sort the may by values in Java 8? (example)
  • How to convert lambda expression to method reference in Java 8 (tutorial)

Thanks for reading this article, if you like this frequently asked questions about default method then please share with your friends and colleagues. If you have any question or doubt then please drop a comment. 

No comments:

Post a Comment