I was going through a Java code and I saw that objects have been allocated using some interface and this interface contains some methods to allocate objects using new
operator. I am unable to think that why they have used an interface instead of just directly allocating objects using new
operator. e.g:
Animal animal = new Animal();
OR
Animal animal = interface.allocateAnimal()
here interface
is an interface having a method allocateAnimal
which does nothing but
new Animal()
.
So ultimately we are doing same thing but in different way so what are gaining here?
EDIT 1: Actually interface is implemented somewhere else. So interface does not contain any implementation code, it just contains methods.