Interface maturity through versions of Java and Kotlin

Tram Ho

In Java or Kotlin, there is no multiple inheritance, to overcome this, the programmer has used the interface

Although there are certain limitations when using the interface, over many versions of Java and Kotlin, the interface has become more and more powerful over time.

Today we will look together to see what the interface will have featured in the versions

1. Interface in Java 7

In Java 7, an interface can only declare two types:

  1. Constants (Constant Variables)
  2. Abstract Method

Interface methods in this version are not allowed to have function bodies

Class implement interface must reinstall the methods in the interface

Now let us consider a small problem: There are 3 classes A, B, C together implement interface OnCheckNumberListener

isEvenNumber() , all 3 class A, B, C must install the method isEvenNumber() as follows:

Obviously, the isEvenNumber() is required to rewrite in all 3 class A, B, C but their content is exactly the same.

Doing so will not optimize the reuse of the source code

To solve this problem, in Java 7, we can create an abstract class to implement the isEvenNumber()

And now, in 3 class A, B, C will not have to reinstall isEvenNumber method when extends class CheckNumber

This may seem good, but keep in mind that Java does not support multiple inheritance, so this is only possible when A, B, C not inherited any previous parent class.

2. Interface in Java 8

In Java 8, in addition to constants and abstract methods, we can declare the default methods (static methods) and static methods (static methods).

  1. Constants (Constant Variables)
  2. Abstract Method
  3. Default method
  4. Static method

Perhaps with this improvement in Java 8, we will no longer need to create an abstract class CheckNumber , which can be installed in the interface

However, our default functions are not always short, they can be so long that we want to separate them into smaller functions.

Then, because they are in an interface, the separated functions will have to be public, but this does not seem to be what we want.

3. Interface in Java 9

Java 9 introduced private and private static methods in interface .

  1. Constant
  2. Abstract method
  3. The default method
  4. Static method
  5. Private method
  6. Private static method


Thereby you can see, Interface is increasingly improved through many versions, supporting a lot of specials that can be overcome more thoroughly than its non-inherited multi-inheritance support. In the next article, let us Let’s discuss about the highlights of Interface in Kotlin.

Share the news now

Source : Viblo