4

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.

Adam Arold
  • 29,285
  • 22
  • 112
  • 207
SIGSTP
  • 1,125
  • 2
  • 9
  • 21

3 Answers3

6

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.

Community
  • 1
  • 1
Adam Arold
  • 29,285
  • 22
  • 112
  • 207
4

It's a design pattern called Factory Method.

Note: while a class has an API (application programming interface), "interface" on it's own has a special meaning/ is a key word in Java. As your example has an implementation of the method it cannot be an interface.

Edit

If it's really a Java interface, then you might see an implementation of the Abstract Factory design pattern: http://en.wikipedia.org/wiki/Abstract_factory_pattern

Puce
  • 37,247
  • 13
  • 80
  • 152
2

I don't think there is actually any code in the interface, since an interface cannot have implementation.

However, the reason why you would like to use an interface.allocateAnimal(), is that sometimes you don't know which animal you want to get a new from. It could be a horse, dog, cat etc.

Only in runtime do you know. So the interface object will in runtime be an implementation, for instance Cat, and the Cat object will have a new Cat() which it will return.

Shervin Asgari
  • 23,901
  • 30
  • 103
  • 143