Programming language Java doesn’t allow multiple inheritances. Java uses interfaces to simulate multiple inheritances without importing its disadvantages. The cost of this is that method implementation was not possible in interfaces until JDK 8.

JDK 8 contains a new feature which allows us to create default implementation for interface methods. Simply just add keyword “default” before the method definition and add implementation body for it. With this, the method will have a default implementation and we don’t need to override them anymore. Basically, we went a step toward multiple inheritances.

As always, there are few disadvantages which came with this feature. We will get a compile error if we have multiple default implementation for the same method. It can be fixed by overriding the method with a new implementation or explicitly call the chosen default method.

The bigger disadvantage is that we can override the default methods in super classes, and in this case, Java won’t give an error or a warning message.

SuperClass-InterFace-PageClass

This applies for all super classes on every level and not just the first one. If we accidentally create a method with name, which already exists in one of the super classes then the default method will be overridden without our knowledge.

This mean we can’t write a default method for methods from Object class because it will never execute. It will also give a compile error.

Let’s see where can we use this feature in test automation code. A Common case is that we have a bunch of page objects which can be grouped by multiple ways. We can group them by using inheritance, or on the other hand, interfaces. To implement a common method for multiple page objects using interface we need to develop the following approach:

Interface

First of all, the definition of the common method must be in the common interface. The implementation of the desired method need to be placed in a separated class which is implementing the interface (also know as: interface impl. or the implementation of the interface). All affected page objects should implement the same interface and have a field with an instance of the interface implementation class. In this way the page object will have the same methods overridden and all of those methods will call the same (already implemented) methods from the interface implementation class. One page object can be in multiple groups, therefore, one page object class can implement more than one interface and hold more than one interface implementation as its own field.

With Java 8 we can implement the common methods in the interface as default method.

The following diagram of this solution is very simple:

Interface-PageClass

We don’t need to implement the methods defined by the interface in a totally separated class anymore. With this we can develop more clean and less hollow implementation of page objects, which is awesome.

Similar Posts from the author: