Top 5 Java 8 Default Methods Interview Questions and Answers

Hello guys, If you are preparing for Java interviews and want to learn about default methods in Java then you have come to the right place. In the last couple of articles, I have to talk about default methods introduced in JDK 8. First, we have learned what is the 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 supports multiple inheritances now in JDK 8 (see here) and how Java handles the diamond problem that will arise due to default methods.
For example, what will happen if a class extends a class and implement an interface and both contain a concrete method with the 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 questions about default methods on Java 8. These are also the most common Java interview questions on default methods. 

In this list, you will find 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 Interview Questions

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

1. Can we make the Default method static in Java? 
No, You cannot make the 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, the 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 an 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 like the sort() method is added into a java.util.List and there is a reversed() method added on the Comparator interface. 

In short, a lot of static and default methods are added to the existing interface to make them better. I suggest you read good Java  8 books or Java 8 courses to learn more about those methods and other Java 8 features.



2. Can an interface contain more than one Default method? 
Yes, any Java interface can contain more than one default method. But, I have yet to find reasons for adding multiple default methods on an interface, because default implies one behavior, not multiple behaviors. Anyway, Java 8 compiler is happy to let you declare more than one default method, 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, the default method cannot override any method from java.lang.Object, trying to override toString(), equals() or hashCode() as the 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 like List.

So why default methods are prevented from overriding equals(), hashCode(), or any other method from the Object class? Brian Goetz answered this question on the project lambda mailing list in detail, one of them is the 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 join The Complete Java MasterClass to learn more about this concept.

Java 8 Default Methods FAQ - Frequently asked Questions and Answers



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 a default method to save there, a normal method will do the job.

5. Can the 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 the interface. Adding a new method inside the 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 the interface then feel free to drop a comment. I'll try to find an answer for you.



Related Java 8 Tutorials
If you are interested in learning more about the 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 use forEach() method in Java 8 (example)
  • Top 5 Courses to learn Full Stack Java development (courses)
  • How to use filter() method in Java 8 (tutorial)
  • 10 Advanced Core Java courses for Programmers (courses)
  • How to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • My favorite free courses to learn Java in-depth (courses)
  • How to use Stream class in Java 8 (tutorial)
  • Top 5 Courses to learn Lambdas and Stream in Java (courses)
  • How to convert List to Map in Java 8 (solution)
  • Best Courses to learn Java Programming for Beginners (best courses)
  • 20 Examples of Date and Time in Java 8 (tutorial)
  • Best Courses to learn Spring Framework (best courses)
  • How to use peek() method in Java 8 (example)
  • best Courses to learn Data structure and Algorithms (best courses)
  • How to sort the map by keys in Java 8? (example)
  • How to sort the may by values in Java 8? (example)
  • 10 examples of Options in Java 8? (example)
  • How to convert lambda expression to method reference in Java 8 (tutorial)
  • 5 Free Java 8 and  Java 9 courses for Programmers (courses)

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

P. S. - If your goal is to learn all new features introduced in Java 8 then you can also check out these best Java features courses from Coursera and Udemy which only focuses on new features and nothing else.

4 comments:

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