k1eriker
k1eriker

Reputation: 11

Java 8 interface - static factory method

Since Java 8 it's possible that interfaces can have static methods. So my question is, does it make sense to have a static factory method in the interface, which instatiates the actual implementation.

Except for the fact that the interfaces would have a dependency to its implemenation, I can't see further disadvantages. Of course in situations where an interface has many implementations, I also wouldn't consider to do that.

What's your opinion on that?

Upvotes: 1

Views: 1466

Answers (1)

Vasu
Vasu

Reputation: 22432

Except for the fact that the interfaces would have a dependency to its implemenation, I can't see further disadvantages. Of course in situations where an interface has many implementations, I also wouldn't consider to do that.

The entire concept of "coding to interfaces" is to decouple the interfaces with the implementation classes so that it will give us the flexibility to inject/pass different objects at runtime and get the dynamic behaviour.

So, in short, if you hard code the interface with implementation (even if it is single implementation), then your code is tightly coupled and you are breaking open closed principle (classes should be flexible/open for extension and closed for modifications), which is not recommended.

Upvotes: 1

Related Questions