When Should I Use an Interface in Java

When should I use an interface in java?

Use interfaces to define an application programming contract (blueprint, interface) which "3rd-party" vendors have to fully adhere and implement. This way the endusers can just code against the API contract and easily switch of the concrete implementation "under the hoods" without changing the code.

The JDBC API is an excellent example. It exist of almost only interfaces. The concrete implementations are provided as "JDBC drivers". This enables you to write all the JDBC code independent of the database (DB) vendor. You can just change the JDBC driver without changing any line of Java code (except of any hardcoded DB-specific SQL code) whenever you'd like to switch of DB vendor.

Another example is the Java EE API, it also contains pretty much interfaces and abstract classes. The concrete implementations are provided as "Java EE application servers", "Servletcontainers", etc, such as Sun Glassfish, Apache Tomcat, etc. This enables you to deploy the webapplication (WAR) to whatever Java web server you like.

Should you always Code To Interfaces In Java

In general I agree with the other answers: use an interface when you know or anticipate change and/or different implementation, or go for testability.

But it's not always easy to know in advance what may change in the future, especially if you are not so experienced. I think the solution for that problem is refactoring: keep it simple (= no interface) as long as it is not needed. When the need arises simply do an "Introduce/Extract interface" refactoring (supported by almost all decent IDEs).

When you do it extract only those methods that are actually needed by the callers. Don't be afraid to extract more then one separate interfaces (if not all of the extracted methods are really coherent).

One driver of the refactoring might be the testing: if you can't easily test something with classes only consider introducing one/some interface(s). This will also allow you to use mocking which may greatly simplify testing in many cases.

Edit: based on Tarski's comment I've realized one more important scenario/adjustment to the previous statements:

If you provide an external API (for other [sub]projects, or really release it "to the wild") then using interfaces in the API (except for simple value classes) is almost always a good idea.

It will allow you to change the impl if you like without disturbing the client code. You will have a problem only if you also have to change the interface. Not breaking compatibility will be very tricky (if not impossible).

When should one use interfaces?

In languages such as Java and C# interfaces provide a means for a class to be have in a polymorphic manner. That is to say a class can satisfy more than one contract - it can behave as multiple different types, a class of one type can be substituted for another. In other languages this can also be provided by multiple inheritance, but there are various disadvantages to this approach. However, having a class behave as more than one type is not the most common motivation for using interfaces.

By programming to interfaces instead of classes you can also decouple your program from specific implementations. This makes it much easier to substitute one class implementation for another. This is particularly useful when writing unit tests where you may wish to swap some heavyweight class implementation with a lightweight mock object. If your program only expects an interface type, and both the heavyweight object and mock object implement said interface, then they are very easy to substitute.

Also, consider a simple Java example where I say have a program that displays pages of data on the screen. Initially I want it to get the data from a database or XML files. If I write my program so that it uses interfaces I can define an interface like so:

public interface PageDatasource {
public List<Page> getPages();
}

And use it like so:

PageDatasource datasource = // insert concrete PageDatasource implementation here
List<Pages> pages = datasource.getPages();
display(pages);

I can then write separate database and XML implementations that adhere to this interface:

public class DatabasePageDatasource implements PageDatasource {
public List<Page> getPages() {
// Database specific code
}
}

public class XmlPageDatasource implements PageDatasource {
public List<Page> getPages() {
// XML specific code
}
}

Because I used an interface I can now use either implementation - Database or XML - interchangeably without having to change the parts of my program that ask for the page data. The XML and Database implementations likely do completely different things but all my program cares about is that the object supplying the page data implements the PageDatasource interface.

When should I use an interface vs an implementation when declaring a new object?

It's ok to use both, but the former is preferred because it's always better to call an implementation's method using a reference to the Interface or super type (List). The former doesn't depend on the implementation and eliminates the need to change the code when the implementation (ArrayList) changes, but the latter requires you to change the code when the implementation changes to anything other than ArrayList.

Why should we use interface if we can simply override methods of the superclass or use abstract classes?

To explain why interfaces are used, you have to first understand a problem with inheritance. It's called the Diamond Problem. Simply, if a class, D inherits from two classes B and C, and B and C both inherit from the same class A, which implementation of the methods from A does D get?

Sample Image

What we're left with is a method ambiguity that Java does not like! So the way of preventing this is to make sure that D can only ever have one superclass, so it could inherit from either A, B or C, but never more than one. So that prevents the problem, but we lose all of the perks that multiple inheritance offers!

Enter the Interface. This allows us to have the perks of multiple inheritance (referencing the single class as various different types) and still avoid the diamond problem, because the implementing class provides the method. This removes the method ambiguity.

This means that, for example:

public abstract class MyClass {
public void doSomething();
}

public class MyConcreteClass extends MyClass {
public void doSomething() {
// do something
}
}

You can either refer to an instance of MyConcreteClass as

 MyClass class = new MyConcreteClass();

or

 MyConcreteClass class = new MyConcreteClass();

But never anything else, given this implementation. You can't extend more classes because you'll potentially get the diamond problem, but you CAN include an Interface

public class MyConcreteClass extends MyClass implements Serializable {
}

All of a sudden, you can say..

Seralizable myClass = new MyConcreteClass();

Because myClass is a Serializable. This is excellent for decoupling classes from one another, when a method might not need to know that it is an instance of MyConcreteClass, only that it has a necessary subset of methods.

In short: You can implement many interfaces, but you can only inherit one class.

When do I have to use interfaces instead of abstract classes?

From Java How to Program about abstract classes:

Because they’re used only as superclasses in inheritance hierarchies,
we refer to them as abstract superclasses. These classes cannot be
used to instantiate objects, because abstract classes are incomplete.

Subclasses must declare the “missing pieces” to become “concrete” classes,
from which you can instantiate objects. Otherwise, these subclasses, too,
will be abstract.

To answer your question "What is the reason to use interfaces?":

An abstract class’s purpose is to provide an appropriate superclass
from which other classes can inherit and thus share a common design.

As opposed to an interface:

An interface describes a set of methods that can be called on an
object, but does not provide concrete implementations for all the
methods
... Once a class implements an interface, all objects of that class have
an is-a relationship with the interface type, and all objects of the
class are guaranteed to provide the functionality described by the
interface.
This is true of all subclasses of that class as well.

So, to answer your question "I was wondering when I should use interfaces", I think you should use interfaces when you want a full implementation and use abstract classes when you want partial pieces for your design (for reusability)

When to use an interface instead of an abstract class and vice versa?

I wrote an article about that:

Abstract classes and interfaces

Summarizing:

When we talk about abstract classes we are defining characteristics of an object type; specifying what an object is.

When we talk about an interface and define capabilities that we promise to provide, we are talking about establishing a contract about what the object can do.

Why should I use an interface when there is only one implementation class?

You do this to prevent others from accessing your implementing type. For example, you could hide your implementing type inside a library, give the type package access, and return an instance of your interface to the users of your library:

// This is what the users of your library know about the class
// that does the work:
public interface SomeInterface {
void doSomethingUseful();
void doSomethingElse();
}

// This is the class itself, which is hidden from your clients
class MyImplementation implements SomeInterface {
private SomeDependency dependency = new SomeDependency();
public void doSomethingUseful() {
...
}
public void doSomethingElse() {
...
}
}

Your clients obtain objects like this:

public class MyFactory {
static SomeInterface make() {
// MyFactory can see MyImplementation
return new MyImplementation();
}
}

This trick becomes useful when the implementation uses lots of libraries. You efficiently decouple the interface of your library from its implementation, so that the user wouldn't have to know about the dependencies internal to your library.



Related Topics



Leave a reply



Submit