Interface Evolution (Java 7, Java 8, Java 9)

Hello guys, this blog is from Java 8 as well as Java 9 and we are going to talk about the interface and its members. Later on, we will see the difference between an interface and an abstract class.

I have already posted a few topics from Java 8. Here are the links

Prior to Java 8, an interface can have constant variables and abstract methods. Any class wants to implement an interface, has to implement all its methods. See the example below.

In the above example, I have declared an interface Message in which, there is an abstract method — printMessage(). Two different classes have provided the implementation of the abstract method. Now, what if I introduce another abstract method say — init(). In this case, all concrete classes have to implement. There might be a possibility that some of the concrete classes are interested in overriding and some are not. What if I want to declare a method which cannot be overridden but available for use by everyone.

To solve the above problems, Java 8 introduced two more members to an interface.

  • Default methods
  • Static methods

Default and static methods allow you to provide implementation at the interface level itself. With respect to default methods, it is up to the concrete classes whether to override it or use it as it is. Static methods in an interface are similar to static methods in a class.

One problem I see in default and static methods is that my implementation is complex and too many lines of code. Need something to break it into smaller chunks.

In Java 9, private methods were introduced to solve the above problem. You can create private methods as well as private static methods. See the example given below.

These private methods will improve code reusability inside interfaces and will give an option to expose only the intended methods.

Let us see the list of members that we can have in an interface in Java 9

  • Constant variables
  • Abstract methods
  • Default methods
  • Static methods
  • Private methods
  • Private static methods

Now we see the interface to be as powerful as abstract class. But do you see it as a replacement? The answer is simply no because abstract classes can do a lot more, such as

  • Abstract classes can have access specifiers for their methods and variables whereas an interface is always public and variables are always constant ie it cannot maintain any state information.

Here we conclude with this blog. Hope you guys understood the features introduced and the difference between an abstract class and an interface.

Thank You.