Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object Allocation through new operator or some interface

Tags:

java

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.

like image 325
SIGSTP Avatar asked Dec 16 '22 10:12

SIGSTP


1 Answers

First of all interfaces 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.

like image 175
Adam Arold Avatar answered Dec 29 '22 12:12

Adam Arold