Explaining ‘private’ interface methods
Interfaces can also have private
methods with code implementations. They were introduced to reduce code duplication and improve encapsulation. These private
methods can be both static
and non-static. As they are private
, they can only be accessed from within the interface. As with classes, you cannot access a non-static method from a static
method.
Let’s have a look at an example in code. Firstly, we will examine code that has code duplication. Figure 10.8 shows such an interface:
Figure 10.8 – An interface with code duplication
As this figure shows, lines 6, 11, and 16 are the same. In addition, lines 8, 13, and 18 are also the same. We will refactor this interface to address this code duplication by using private
methods. Figure 10.9 shows the code for this:
Figure 10.9 – An interface with private methods
In this figure, we have a private
static...