Java 8 Interface : What’s new?

HarshaVardhanReddy Bommareddy
2 min readDec 31, 2020

--

Photo by Caspar Camille Rubin on Unsplash

Let’s get started with our obvious questions What and Why?

What?

  • Prior to Java 8, we could have only abstract methods.
  • Now we can also have Default and Static methods in an Interface

Why?

  • As Interface grows old, it would be troublesome changing all the required classes as we have to keep adding the new methods of Interface
  • In other words adding new methods to existing interfaces will help developers in a such a way that they are backward compatible
  • Static methods are same as Default methods but only we cannot override static methods in the classes that implements those interfaces
interface MyInterface{  

default void newDefaultMethod(){
System.out.println("Default method");
}
void existingAbstractMethod(String str);
}

From the above code it’s not mandatory to implement the newDefaultMethod() in any class that implements MyInteface.

interface MyInterface{  

static void newStaticMethod(){
System.out.println("static method");
}
void existingAbstractMethod(String str);
}

Since the newStaticMethod() is static method we cannot override them in implementation classes. Simply we can add them in the existing interfaces without changing the code in implementation classes.

By this we will not be able to achieve full abstraction even by using Interfaces and there would be no difference between Abstract Class and Interface. That’s not true, even in Java 8 we cannot have constructor for Interface whereas for abstract class we can.

And Interfaces providing full abstraction is still true even if we have default methods. Adding default methods is to simply add new features to interfaces without effecting existing classes.

Conclusion

  • Default methods has brought down the differences between Interface and Abstract Classes
  • Default methods will help in removing base implementation classes
  • Static methods are useful for providing utility methods
  • Static methods provide security by not allowing implementation classes to override them

Drop your comments and suggestions.

Thanks for reading!
Keep Coding!

--

--