Interface Segregation Principle in java

In this tutorial, we will learn about Interface Segregation Principle.It is one of the SOLID principles.
In simple term, Interface Segregation Principle dictates that client should not be forced to implement the methods which it won’t be able to use.You can always throw UnsupportedOperationException from the method which you don’t want to use but it is not recommended and it makes your class tough to use.

Let’s understand with the help of a simple example.
Assume we have created simple Set interface as below.

Create a class TreeSet.java as below.

Create another class HashSet.java as below.

Do you see the problem, even though you do not require ceiling and floor method in HashSet, we have to implement them.
The correct solution for above problem will be:
Create another interface called NavigableSet which will have ceiling and floor method.

and Set interface will be changed as below

Now TreeSet.java will be going to implement two interfaces Set and NavigableSet. Change TreeSet.java as below.

HashSet will be going to implement only Set as it does not require ceiling and floor methods.

As you can see here, HashSet does not implement any method which it does not require.
That’s all about Interface Segregation Principle in java

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *