<p>Almost every Java book I read talks about using the interface as a way to share state and behaviour between objects that when first "constructed" did not seem to share a relationship. </p>

<p>However, whenever I see architects design an application, the first thing they do is start programming to an interface. How come? How do you know all the relationships between objects that will occur within that interface? If you already know those relationships, then why not just extend an abstract class?</p>

[{'answer_id': 48611, 'author': 'Brian Warshaw', 'author_id': 1344, 'author_profile': 'https://Stackoverflow.com/users/1344', 'pm_score': 6, 'selected': True, 'text': '<p>Programming to an interface means respecting the "contract" created by using that interface. And so if your <code>IPoweredByMotor</code> interface has a <code>start()</code> method, future classes that implement the interface, be they <code>MotorizedWheelChair</code>, <code>Automobile</code>, or <code>SmoothieMaker</code>, in implementing the methods of that interface, add flexibility to your system, because one piece of code can start the motor of many different types of things, because all that one piece of code needs to know is that they respond to <code>start()</code>. It doesn\'t matter <em>how</em> they start, just that they <em>must start</em>.</p>\n'}, {'answer_id': 48624, 'author': 'Eugene Yokota', 'author_id': 3827, 'author_profile': 'https://Stackoverflow.com/users/3827', 'pm_score': 2, 'selected': False, 'text': '<p>It\'s one way to promote loose <a href="http://en.wikipedia.org/wiki/Coupling_%28computer_science%29" rel="nofollow noreferrer">coupling</a>.</p>\n\n<blockquote>\n  <p>With low coupling, a change in one module will not require a change in the implementation of another module. </p>\n</blockquote>\n\n<p>A good use of this concept is <a href="http://en.wikipedia.org/wiki/Abstract_factory_pattern" rel="nofollow noreferrer">Abstract Factory pattern</a>. In the Wikipedia example, GUIFactory interface produces Button interface. The concrete factory may be WinFactory (producing WinButton), or OSXFactory (producing OSXButton). Imagine if you are writing a GUI application and you have to go look around all instances of <code>OldButton</code> class and changing them to <code>WinButton</code>. Then next year, you need to add <code>OSXButton</code> version.</p>\n'}, {'answer_id': 48631, 'author': 'Bjorn Reppen', 'author_id': 1324220, 'author_profile': 'https://Stackoverflow.com/users/1324220', 'pm_score': 4, 'selected': False, 'text': '<p>I think one of the reasons abstract classes have largely been abandoned by developers might be a misunderstanding.</p>\n\n<p>When the <a href="http://en.wikipedia.org/wiki/Gang_of_Four_(software)" rel="noreferrer">Gang of Four</a> wrote:</p>\n\n<blockquote>\n  <p>Program to an interface not an implementation.</p>\n</blockquote>\n\n<p>there was no such thing as a java or C# interface.  They were talking about the object-oriented interface concept, that every class has.  Erich Gamma mentions it in <a href="http://www.artima.com/lejava/articles/designprinciples2.html" rel="noreferrer">this interview</a>.</p>\n\n<p>I think following all the rules and principles mechanically without thinking leads to a difficult to read, navigate, understand and maintain code-base.  Remember: The simplest thing that could possibly work.  </p>\n'}, {'answer_id': 48649, 'author': 'Danimal', 'author_id': 2757, 'author_profile': 'https://Stackoverflow.com/users/2757', 'pm_score': 2, 'selected': False, 'text': "<p>I would assume (with @eed3s9n) that it's to promote loose coupling. Also, without interfaces unit testing becomes much more difficult, as you can't mock up your objects.</p>\n"}, {'answer_id': 48651, 'author': 'Tom', 'author_id': 4459, 'author_profile': 'https://Stackoverflow.com/users/4459', 'pm_score': 0, 'selected': False, 'text': '<p>In one sense, I think your question boils down to simply, "why use interfaces and not abstract classes?" Technically, you can achieve loose coupling with both -- the underlying implementation is still not exposed to the calling code, and you can use Abstract Factory pattern to return an underlying implementation (interface implementation vs. abstract class extension) to increase the flexibility of your design. In fact, you could argue that abstract classes give you slightly more, since they allow you to both require implementations to satisfy your code ("you MUST implement start()") and provide default implementations ("I have a standard paint() you can override if you want to") -- with interfaces, implementations must be provided, which over time can lead to brittle inheritance problems through interface changes.</p>\n\n<p>Fundamentally, though, I use interfaces mainly due to Java\'s single inheritance restriction. If my implementation MUST inherit from an abstract class to be used by calling code, that means I lose the flexibility to inherit from something else even though that may make more sense (e.g. for code reuse or object hierarchy).</p>\n'}, {'answer_id': 48685, 'author': 'John Vasileff', 'author_id': 5076, 'author_profile': 'https://Stackoverflow.com/users/5076', 'pm_score': 4, 'selected': False, 'text': '<p>Programming to interfaces provides several benefits:</p>\n\n<ol>\n<li><p>Required for GoF type patterns, such as the visitor pattern</p></li>\n<li><p>Allows for alternate implementations.  For example, multiple data access object implementations may exist for a single interface that abstracts the database engine in use (AccountDaoMySQL and AccountDaoOracle may both implement AccountDao)</p></li>\n<li><p>A Class may implement multiple interfaces.  Java does not allow multiple inheritance of concrete classes.</p></li>\n<li><p>Abstracts implementation details.  Interfaces may include only public API methods, hiding  implementation details.  Benefits include a cleanly documented public API and well documented contracts.</p></li>\n<li><p>Used heavily by modern dependency injection frameworks, such as <a href="http://www.springframework.org/" rel="nofollow noreferrer">http://www.springframework.org/</a>.</p></li>\n<li><p>In Java, interfaces can be used to create dynamic proxies - <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/Proxy.html" rel="nofollow noreferrer">http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/Proxy.html</a>.  This can be used very effectively with frameworks such as Spring to perform Aspect Oriented Programming. Aspects can add very useful functionality to Classes without directly adding java code to those classes.  Examples of this functionality include logging, auditing, performance monitoring, transaction demarcation, etc.  <a href="http://static.springframework.org/spring/docs/2.5.x/reference/aop.html" rel="nofollow noreferrer">http://static.springframework.org/spring/docs/2.5.x/reference/aop.html</a>.</p></li>\n<li><p>Mock implementations, unit testing - When dependent classes are implementations of interfaces, mock classes can be written that also implement those interfaces.  The mock classes can be used to facilitate unit testing.</p></li>\n</ol>\n'}, {'answer_id': 49290, 'author': 'Jonathan', 'author_id': 1772, 'author_profile': 'https://Stackoverflow.com/users/1772', 'pm_score': 5, 'selected': False, 'text': '<p>Great question. I\'ll refer you to <a href="http://java.sun.com/docs/books/effective/" rel="noreferrer">Josh Bloch in Effective Java</a>, who writes (item 16) why to prefer the use of interfaces over abstract classes. By the way, if you haven\'t got this book, I highly recommend it! Here is a summary of what he says:</p>\n\n<ol>\n<li><strong>Existing classes can be easily retrofitted to implement a new interface.</strong> All you need to do is implement the interface and add the required methods. Existing classes cannot be retrofitted easily to extend a new abstract class.</li>\n<li><strong>Interfaces are ideal for defining mix-ins.</strong> A mix-in interface allows classes to declare additional, optional behavior (for example, Comparable). It allows the optional functionality to be mixed in with the primary functionality. Abstract classes cannot define mix-ins -- a class cannot extend more than one parent.</li>\n<li><strong>Interfaces allow for non-hierarchical frameworks.</strong> If you have a class that has the functionality of many interfaces, it can implement them all. Without interfaces, you would have to create a bloated class hierarchy with a class for every combination of attributes, resulting in combinatorial explosion.</li>\n<li><strong>Interfaces enable safe functionality enhancements.</strong> You can create wrapper classes using the Decorator pattern, a robust and flexible design. A wrapper class implements and contains the same interface, forwarding some functionality to existing methods, while adding specialized behavior to other methods. You can\'t do this with abstract methods - you must use inheritance instead, which is more fragile.</li>\n</ol>\n\n<p>What about the advantage of abstract classes providing basic implementation? You can provide an abstract skeletal implementation class with each interface. This combines the virtues of both interfaces and abstract classes. Skeletal implementations provide implementation assistance without imposing the severe constraints that abstract classes force when they serve as type definitions. For example, the <a href="http://java.sun.com/docs/books/tutorial/collections/index.html" rel="noreferrer">Collections Framework</a> defines the type using interfaces, and provides a skeletal implementation for each one.</p>\n'}, {'answer_id': 50855, 'author': 'Jay Stramel', 'author_id': 3547, 'author_profile': 'https://Stackoverflow.com/users/3547', 'pm_score': 2, 'selected': False, 'text': "<p>In my opinion, you see this so often because it is a very good practice that is often applied in the wrong situations.</p>\n\n<p>There are many advantages to interfaces relative to abstract classes:</p>\n\n<ul>\n<li>You can switch implementations w/o re-building code that depends on the interface.  This is useful for: proxy classes, dependency injection, AOP, etc.</li>\n<li>You can separate the API from the implementation in your code.  This can be nice because it makes it obvious when you're changing code that will affect other modules.</li>\n<li>It allows developers writing code that is dependent on your code to easily mock your API for testing purposes.</li>\n</ul>\n\n<p>You gain the most advantage from interfaces when dealing with modules of code.  However, there is no easy rule to determine where module boundaries should be.  So this best practice is easy to over-use, especially when first designing some software.</p>\n"}, {'answer_id': 50873, 'author': 'Jonathan Allen', 'author_id': 5274, 'author_profile': 'https://Stackoverflow.com/users/5274', 'pm_score': 3, 'selected': False, 'text': "<p><strong>How come?</strong> </p>\n\n<p>Because that's what all the books say. Like the GoF patterns, many people see it as universally good and don't ever think about whether or not it is really the right design.</p>\n\n<p><strong>How do you know all the relationships between objects that will occur within that interface?</strong> </p>\n\n<p>You don't, and that's a problem. </p>\n\n<p><strong>If\nyou already know those relationships,\nthen why not just extend an abstract\nclass?</strong></p>\n\n<p>Reasons to not extend an abstract class:</p>\n\n<ol>\n<li>You have radically different implementations and making a decent base class is too hard.</li>\n<li>You need to burn your one and only base class for something else.</li>\n</ol>\n\n<p>If neither apply, go ahead and use an abstract class. It will save you a lot of time.</p>\n\n<p>Questions you didn't ask:</p>\n\n<p><strong>What are the down-sides of using an interface?</strong></p>\n\n<p>You cannot change them. Unlike an abstract class, an interface is set in stone. Once you have one in use, extending it will break code, period.</p>\n\n<p><strong>Do I really need either?</strong></p>\n\n<p>Most of the time, no. Think really hard before you build any object hierarchy. A big problem in languages like Java is that it makes it way too easy to create massive, complicated object hierarchies.</p>\n\n<p>Consider the classic example LameDuck inherits from Duck. Sounds easy, doesn't it?</p>\n\n<p>Well, that is until you need to indicate that the duck has been injured and is now lame. Or indicate that the lame duck has been healed and can walk again. Java does not allow you to change an objects type, so using sub-types to indicate lameness doesn't actually work.</p>\n"}, {'answer_id': 276429, 'author': 'Anjisan', 'author_id': 25304, 'author_profile': 'https://Stackoverflow.com/users/25304', 'pm_score': 0, 'selected': False, 'text': "<p>One reason is that interfaces allow for growth and extensibility.  Say, for example, that you have a method that takes an object as a parameter,</p>\n\n<p>public void drink(coffee someDrink)\n{</p>\n\n<p>}</p>\n\n<p>Now let's say you want to use the exact same method, but pass a hotTea object.  Well, you can't.  You just hard-coded that above method to only use coffee objects.  Maybe that's good, maybe that's bad.  The downside of the above is that it strictly locks you in with one type of object when you'd like to pass all sorts of related objects.</p>\n\n<p>By using an interface, say IHotDrink,</p>\n\n<p>interface IHotDrink { }</p>\n\n<p>and rewrting your above method to use the interface instead of the object,</p>\n\n<p>public void drink(IHotDrink someDrink)\n{</p>\n\n<p>}</p>\n\n<p>Now you can pass all objects that implement the IHotDrink interface.  Sure, you can write the exact same method that does the exact same thing with a different object parameter, but why?  You're suddenly maintaining bloated code. </p>\n"}, {'answer_id': 276509, 'author': 'Eek', 'author_id': 18752, 'author_profile': 'https://Stackoverflow.com/users/18752', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html" rel="nofollow noreferrer">Why extends is evil</a>. This article is pretty much a direct answer to the question asked.  I can think of almost no case where you would actually <em>need</em> an abstract class, and plenty of situations where it is a bad idea. This does not mean that implementations using abstract classes are bad, but you will have to take care so you do not make the interface contract dependent on artifacts of some specific implementation (case in point: the Stack class in Java).</p>\n\n<p>One more thing: it is not necessary, or good practice, to have interfaces everywhere. Typically, you should identify when you need an interface and when you do not. In an ideal world, the second case should be implemented as a final class most of the time.  </p>\n'}, {'answer_id': 368287, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n  <p>Programming to an interface means respecting the "contract" created by \n  using that interface</p>\n</blockquote>\n\n<p>This is the single most misunderstood thing about interfaces. </p>\n\n<p>There is no way to enforce any such contract with interfaces. Interfaces, by definition, cannot specify any behaviour at all. Classes are where behaviour happens.</p>\n\n<p>This mistaken belief is so widespread as to be considered the conventional wisdom by many people. It is, however, wrong. </p>\n\n<p>So this statement in the OP</p>\n\n<blockquote>\n  <p>Almost every Java book I read talks about using the interface as a way \n  to share state and behavior between objects </p>\n</blockquote>\n\n<p>is just not possible. Interfaces have neither state nor behaviour. They can define properties, that implementing classes must provide, but that\'s as close as they can get. You cannot share behaviour using interfaces.</p>\n\n<p>You can make an assumption that people will implement an interface to provide the sort of behaviour implied by the name of its methods, but that\'s not anything like the same thing. And it places no restrictions at all on when such methods are called (eg that Start should be called before Stop).</p>\n\n<p>This statement</p>\n\n<blockquote>\n  <p>Required for GoF type patterns, such as the visitor pattern</p>\n</blockquote>\n\n<p>is also incorrect. The GoF book uses exactly zero interfaces, as they were not a feature of the languages used at the time. None of the patterns require interfaces, although some can use them. IMO, the Observer pattern is one in which interfaces can play a more elegant role (although the pattern is normally implemented using events nowadays). In the Visitor pattern it is almost always the case that a base Visitor class implementing default behaviour for each type of visited node is required, IME.</p>\n\n<p>Personally, I think the answer to the question is threefold:</p>\n\n<ol>\n<li><p>Interfaces are seen by many as a silver bullet (these people usually labour under the "contract" misapprehension, or think that interfaces magically decouple their code)</p></li>\n<li><p>Java people are very focussed on using frameworks, many of which (rightly) require classes to implement their interfaces</p></li>\n<li><p>Interfaces were the best way to do some things before generics and annotations (attributes in C#) were introduced.</p></li>\n</ol>\n\n<p>Interfaces are a very useful language feature, but are much abused. Symptoms include:</p>\n\n<ol>\n<li><p>An interface is only implemented by one class</p></li>\n<li><p>A class implements multiple interfaces. Often touted as an advantage of interfaces, usually it means that the class in question is violating the principle of separation of concerns.</p></li>\n<li><p>There is an inheritance hierarchy of interfaces (often mirrored by a hierarchy of classes). This is the situation you\'re trying to avoid by using interfaces in the first place. Too much inheritance is a bad thing, both for classes and interfaces.</p></li>\n</ol>\n\n<p>All these things are code smells, IMO.</p>\n'}, {'answer_id': 368400, 'author': 'James Anderson', 'author_id': 38207, 'author_profile': 'https://Stackoverflow.com/users/38207', 'pm_score': 0, 'selected': False, 'text': '<p>Its all about designing before coding.</p>\n\n<p>If you dont know all the relationships between two objects after you have specified the interface then you have done a poor job of defining the interface -- which is relatively easy to fix. </p>\n\n<p>If you had dived straight into coding and realised half way through you are missing something its a lot harder to fix. </p>\n'}, {'answer_id': 470193, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>There are some excellent answers here, but if you\'re looking for a concrete reason, look no further than Unit Testing.</p>\n\n<p>Consider that you want to test a method in the business logic that retrieves the current tax rate for the region where a transaction occurrs. To do this, the business logic class has to talk to the database via a Repository:</p>\n\n<pre><code>interface IRepository&lt;T&gt; { T Get(string key); }\n\nclass TaxRateRepository : IRepository&lt;TaxRate&gt; {\n    protected internal TaxRateRepository() {}\n    public TaxRate Get(string key) {\n    // retrieve an TaxRate (obj) from database\n    return obj; }\n}\n</code></pre>\n\n<p>Throughout the code, use the type IRepository instead of TaxRateRepository.</p>\n\n<p>The repository has a non-public constructor to encourage users (developers) to use the factory to instantiate the repository:</p>\n\n<pre><code>public static class RepositoryFactory {\n\n    public RepositoryFactory() {\n        TaxRateRepository = new TaxRateRepository(); }\n\n    public static IRepository TaxRateRepository { get; protected set; }\n    public static void SetTaxRateRepository(IRepository rep) {\n        TaxRateRepository = rep; }\n}\n</code></pre>\n\n<p>The factory is the only place where the TaxRateRepository class is referenced directly.</p>\n\n<p>So you need some supporting classes for this example:</p>\n\n<pre><code>class TaxRate {\n    public string Region { get; protected set; }\n    decimal Rate { get; protected set; }\n}\n\nstatic class Business {\n    static decimal GetRate(string region) { \n        var taxRate = RepositoryFactory.TaxRateRepository.Get(region);\n        return taxRate.Rate; }\n}\n</code></pre>\n\n<p>And there is also another other implementation of IRepository - the mock up:</p>\n\n<pre><code>class MockTaxRateRepository : IRepository&lt;TaxRate&gt; {\n    public TaxRate ReturnValue { get; set; }\n    public bool GetWasCalled { get; protected set; }\n    public string KeyParamValue { get; protected set; }\n    public TaxRate Get(string key) {\n        GetWasCalled = true;\n        KeyParamValue = key;\n        return ReturnValue; }\n}\n</code></pre>\n\n<p>Because the live code (Business Class) uses a Factory to get the Repository, in the unit test you plug in the MockRepository for the TaxRateRepository. Once the substitution is made, you can hard code the return value and make the database unneccessary.</p>\n\n<pre><code>class MyUnitTestFixture { \n    var rep = new MockTaxRateRepository();\n\n    [FixtureSetup]\n    void ConfigureFixture() {\n        RepositoryFactory.SetTaxRateRepository(rep); }\n\n    [Test]\n    void Test() {\n        var region = "NY.NY.Manhattan";\n        var rate = 8.5m;\n        rep.ReturnValue = new TaxRate { Rate = rate };\n\n        var r = Business.GetRate(region);\n        Assert.IsNotNull(r);\n        Assert.IsTrue(rep.GetWasCalled);\n        Assert.AreEqual(region, rep.KeyParamValue);\n        Assert.AreEqual(r.Rate, rate); }\n}\n</code></pre>\n\n<p>Remember, you want to test the business logic method only, not the repository, database, connection string, etc... There are different tests for each of those.  By doing it this way, you can completely isolate the code that you are testing.    </p>\n\n<p>A side benefit is that you can also run the unit test without a database connection, which makes it faster, more portable (think multi-developer team in remote locations).</p>\n\n<p>Another side benefit is that you can use the Test-Driven Development (TDD) process for the implementation phase of development. I don\'t strictly use TDD but a mix of TDD and old-school coding.</p>\n'}, {'answer_id': 470234, 'author': 'Geo', 'author_id': 31610, 'author_profile': 'https://Stackoverflow.com/users/31610', 'pm_score': 0, 'selected': False, 'text': "<p>You could see this from a perl/python/ruby perspective :</p>\n\n<ul>\n<li>when you pass an object as a parameter to a method you don't pass it's type , you just know that it must respond to some methods</li>\n</ul>\n\n<p>I think considering java interfaces as an analogy to that would best explain this . You don't really pass a type , you just pass something that responds to a method ( a trait , if you will ).</p>\n"}, {'answer_id': 1991212, 'author': 'deamon', 'author_id': 238134, 'author_profile': 'https://Stackoverflow.com/users/238134', 'pm_score': 0, 'selected': False, 'text': '<p>I think the main reason to use interfaces in Java is the limitation to single inheritance. In many cases this lead to unnecessary complication and code duplication. Take a look at Traits in Scala: <a href="http://www.scala-lang.org/node/126" rel="nofollow noreferrer">http://www.scala-lang.org/node/126</a> Traits are a special kind of abstract classes, but a class can extend many of them.</p>\n'}]
['https://Stackoverflow.com/questions/48605', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']