OneZero
OneZero

Reputation: 11904

Why separation of interface and implementation?

In production code I often see classes defined as follows:

public interface SomeComponent { // Some methods }
public class SomeComponentImpl implements SomeComponent { // Some methods}

public interface SomeComponentV2 extends SomeComponent { // Some methods }
public class SomeComponentV2Impl extends SomeComponentImpl implements SomeComponent { // Some methods }

Why in this case we want to separate the interface and its implementation?

Or put it this way, why is it bad to simply have one base class, and let V2 extend/override V1 as follows:

public class SomeComponent { // Some methods }
public class SomeComponentV2 extends SomeComponent 
{
  // Override methods for reimplementation
  // Add new methods for new features.
}

Upvotes: 7

Views: 5656

Answers (2)

itwasntme
itwasntme

Reputation: 1462

Separating interface from implementation allows to fully use polymorphism. In this way SomeComponentV2Impl will have 3 types - own, base class, and interface. Here you may just use only the interface without caring about it's implementation in further classes. For example:

public void methodInOuterClass(SomeComponent smCmp){
    smCmp.runInterfaceMethods();
}

[Edit: this question appeared in OP question before edites]

Why do we dont use one base class for them all?

Because SomeComponentV2Impl is distinguish from SomeComponentImpl. But if they implement same interface, you will be able to call their implementation from the interface's refference.

Upvotes: 0

Stefan Wanitzek
Stefan Wanitzek

Reputation: 2124

It is a good practice to separate the interface and the implementation of a class because you can easily swap out classes.

Imagine you want to test a application which depends on a web-service which bills you for every request. In addition to have a class which performs real requests to this web-service, you could build a class which implements the same interface but returns fake data to avoid generating costs for every request.

Every time you inherit from a base-class there is a chance that you inherit behaviour you simply don't want to inherit. An interface is a pure contract and gives you the freedom to let you choose a base-class independently of the described advantage.

Upvotes: 2

Related Questions