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.
First of all interface
s are not allocating anything. They are just establishing contracts.
What you see there is the factory method pattern. Someone decided to implement that interface and the concrete implementation's method is creating an Animal
object. You can check the link to the pattern and there you'll find a thorough explanation about the factory method.
There is a question here about the reasons using the factory pattern it might worth checking out. Here is the point:
...using a Factory allows the consumer to create new objects without having to know the details of how they're created, or what their dependencies are - they only have to give the information they actually want.
There is something more: the person who have written the code you are reading may be tried to refer to the programming interface of something which is not the technical interface
keyword in java. It means something else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With