Uses of Interfaces in Java- there are three main reasons
- To achieve loose coupling
- To achieve abstraction
- To achieve multiple inheritance
Loose coupling
Let’s say we have a interface named Animal and it has three methods walking(), running() and eating()
public interface Animal {
void walking();
void running();
void eating();
}
And we have classes name Dog and Cat which are implementing this interface.
public class Dog implements Animal {
@Override
public void walking() {
System.out.println("Dog is walking");
}
@Override
public void running() {
System.out.println("Dog is running");
}
@Override
public void eating() {
System.out.println("Dog is eating");
}
}
public class Cat implements Animal {
@Override
public void walking() {
System.out.println("Cat is walking");
}
@Override
public void running() {
System.out.println("Cat is running");
}
@Override
public void eating() {
System.out.println("Cat is eating");
}
}
We have a class named MyPet and in the constructor we are taking the instance of a Dog class
public class MyPet {
Dog dog;
public MyPet(Dog dog) {
this.dog = dog;
}
void run() {
dog.running();
}
}
But if you want to get a Cat as a pet then we will have to replace the implementation of Dog with Cat and all the operations and instances would have to be updated.
But if we take the instance of Animal instead of Dog in MyPet class constructor then we would simply have to pass the instance of Cat.
public class MyPet {
Animal animal;
public MyPet(Animal animal) {
this.animal = animal;
}
void run() {
animal.running();
}
}
that’s it, it is called as loose coupling.
Abstraction
It is essentially hiding the implementation details and only revealing the necessary parts to the user.
As you can see in the above example we have called animal.running();
here user knows that when it is called the animal would Run. Now user do not need to know what all operations are going to happen in that method.
Multiple Inheritance
Unlike classes we can implement multiple interfaces with a single class which gives us the opportunity of implementing multiple behaviours
In addition to above example let say we have an interface called Bird which has method flying it is also implemented by AlienDog class
public interface Bird {
void flying();
}
public class AlienDog implements Animal, Bird {
@Override
public void flying() {
System.out.println("AlienDog is flying");
}
@Override
public void walking() {
System.out.println("AlienDog is walking");
}
@Override
public void running() {
System.out.println("AlienDog is running");
}
@Override
public void eating() {
System.out.println("AlienDog is eating");
}
}