<p>When should I use an interface and when should I use a base class? </p>

<p>Should it always be an interface if I don't want to actually define a base implementation of the methods?</p>

<p>If I have a Dog and Cat class. Why would I want to implement IPet instead of PetBase? I can understand having interfaces for ISheds or IBarks (IMakesNoise?), because those can be placed on a pet by pet basis, but I don't understand which to use for a generic Pet.</p>

[{'answer_id': 56871, 'author': 'Jason Cohen', 'author_id': 4926, 'author_profile': 'https://Stackoverflow.com/users/4926', 'pm_score': 7, 'selected': False, 'text': '<p>Modern style is to define IPet <em>and</em> PetBase.</p>\n\n<p>The advantage of the interface is that other code can use it without any ties whatsoever to other executable code.  Completely "clean."  Also interfaces can be mixed.</p>\n\n<p>But base classes are useful for simple implementations and common utilities.  So provide an abstract base class as well to save time and code.</p>\n'}, {'answer_id': 56873, 'author': 'Kilhoffer', 'author_id': 5469, 'author_profile': 'https://Stackoverflow.com/users/5469', 'pm_score': 6, 'selected': False, 'text': '<p>In general, you should favor interfaces over abstract classes. One reason to use an abstract class is if you have common implementation among concrete classes. Of course, you should still declare an interface (IPet) and have an abstract class (PetBase) implement that interface.Using small, distinct interfaces, you can use multiples to further improve flexibility. Interfaces allow the maximum amount of flexibility and portability of types across boundaries. When passing references across boundaries, always pass the interface and not the concrete type. This allows the receiving end to determine concrete implementation and provides maximum flexibility. This is absolutely true when programming in a TDD/BDD fashion.</p>\n\n<p>The Gang of Four stated in their book "Because inheritance exposes a subclass to details of its parent\'s implementation, it\'s often said that \'inheritance breaks encapsulation". I believe this to be true.</p>\n'}, {'answer_id': 56878, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 3, 'selected': False, 'text': "<p>One important difference is that you can only inherit <strong>one</strong> base class, but you can implement <strong>many</strong> interfaces.  So you only want to use a base class if you are <em>absolutely certain</em> that you won't need to also inherit a different base class.  Additionally, if you find your interface is getting large then you should start looking to break it up into a few logical pieces that define independent functionality, since there's no rule that your class can't implement them all (or that you can define a different interface that just inherits them all to group them).</p>\n"}, {'answer_id': 56887, 'author': 'spoulson', 'author_id': 3347, 'author_profile': 'https://Stackoverflow.com/users/3347', 'pm_score': 2, 'selected': False, 'text': "<p>It depends on your requirements.  If IPet is simple enough, I would prefer to implement that.  Otherwise, if PetBase implements a ton of functionality you don't want to duplicate, then have at it.</p>\n\n<p>The downside to implementing a base class is the requirement to <code>override</code> (or <code>new</code>) existing methods.  This makes them virtual methods which means you have to be careful about how you use the object instance.</p>\n\n<p>Lastly, the single inheritance of .NET kills me.  A naive example: Say you're making a user control, so you inherit <code>UserControl</code>.  But, now you're locked out of also inheriting <code>PetBase</code>.  This forces you to reorganize, such as to make a <code>PetBase</code> class member, instead.</p>\n"}, {'answer_id': 56893, 'author': 'Bill the Lizard', 'author_id': 1288, 'author_profile': 'https://Stackoverflow.com/users/1288', 'pm_score': 2, 'selected': False, 'text': "<p>I usually don't implement either until I need one.  I favor interfaces over abstract classes because that gives a little more flexibility.  If there's common behavior in some of the inheriting classes I move that up and make an abstract base class.  I don't see the need for both, since they essentially server the same purpose, and having both is a bad code smell (imho) that the solution has been over-engineered.</p>\n"}, {'answer_id': 56894, 'author': 'Marcio Aguiar', 'author_id': 4213, 'author_profile': 'https://Stackoverflow.com/users/4213', 'pm_score': 7, 'selected': False, 'text': '<p>Well, Josh Bloch said himself in <a href="https://rads.stackoverflow.com/amzn/click/com/0321356683" rel="noreferrer" rel="nofollow noreferrer">Effective Java 2d</a>:</p>\n\n<h2>Prefer interfaces over abstract classes</h2>\n\n<p>Some main points:</p>\n\n<blockquote>\n  <ul>\n  <li><p><strong>Existing classes can be easily retrofitted to implement a new\n  interface</strong>. All you have to do is add\n  the required methods if they don’t yet\n  exist and add an implements clause to\n  the class declaration. </p></li>\n  <li><p><strong>Interfaces are ideal for defining mixins</strong>. Loosely speaking, a\n  mixin is a type that a class can\n  implement in addition to its “primary\n  type” to declare that it provides\n  some optional behavior. For example,\n  Comparable is a mixin interface that\n  allows a class to declare that its\n  instances are ordered with respect to\n  other mutually comparable objects.</p></li>\n  <li><p><strong>Interfaces allow the construction of nonhierarchical type\n  frameworks</strong>. Type hierarchies are\n  great for organizing some things, but\n  other things don’t fall neatly into a\n  rigid hierarchy. </p></li>\n  <li><p><strong>Interfaces enable safe, powerful functionality enhancements</strong> via the\n  wrap- per class idiom. If you use\n  abstract classes to define types, you\n  leave the programmer who wants to add\n  functionality with no alternative but\n  to use inheritance. </p></li>\n  </ul>\n  \n  <p>Moreover, you can combine the virtues\n  of interfaces and abstract classes by\n  providing an abstract skeletal\n  implementation class to go with each\n  nontrivial interface that you export.</p>\n</blockquote>\n\n<p>On the other hand, interfaces are very hard to evolve. If you add a method to an interface it\'ll break all of it\'s implementations.</p>\n\n<p>PS.: Buy the book. It\'s a lot more detailed.</p>\n'}, {'answer_id': 56901, 'author': 'Torlack', 'author_id': 5243, 'author_profile': 'https://Stackoverflow.com/users/5243', 'pm_score': 0, 'selected': False, 'text': '<p>In addition to those comments that mention the IPet/PetBase implementation, there are also cases where providing an accessor helper class can be very valuable.</p>\n\n<p>The IPet/PetBase style assumes that you have multiple implementations thus increasing the value of PetBase since it simplifies implementation.  However, if you have the reverse or a blend of the two where you have multiple clients, providing a class help assist in the usage of the interface can reduce cost by making it easier to use an interface.</p>\n'}, {'answer_id': 56902, 'author': 'Jarrett Meyer', 'author_id': 5834, 'author_profile': 'https://Stackoverflow.com/users/5834', 'pm_score': 3, 'selected': False, 'text': "<p>Interfaces should be small. Really small. If you're really breaking down your objects, then your interfaces will probably only contain a few very specific methods and properties.</p>\n\n<p>Abstract classes are shortcuts. Are there things that all derivatives of PetBase share that you can code once and be done with? If yes, then it's time for an abstract class.</p>\n\n<p>Abstract classes are also limiting. While they give you a great shortcut to producing child objects, any given object can only implement one abstract class. Many times, I find this a limitation of Abstract classes, and this is why I use lots of interfaces.</p>\n\n<p>Abstract classes may contain several interfaces. Your PetBase abstract class may implement IPet (pets have owners) and IDigestion (pets eat, or at least they should). However, PetBase will probably not implement IMammal, since not all pets are mammals and not all mammals are pets. You may add a MammalPetBase that extends PetBase and add IMammal. FishBase could have PetBase and add IFish. IFish would have ISwim and IUnderwaterBreather as interfaces.</p>\n\n<p>Yes, my example is extensively over-complicated for the simple example, but that's part of the great thing about how interfaces and abstract classes work together.</p>\n"}, {'answer_id': 56912, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 10, 'selected': True, 'text': '<p>\nLet\'s take your example of a Dog and a Cat class, and let\'s illustrate using C#:</p>\n\n<p>Both a dog and a cat are animals, specifically, quadruped mammals (animals are waaay too general). Let us assume that you have an abstract class Mammal, for both of them:</p>\n\n<pre class="lang-cs prettyprint-override"><code>public abstract class Mammal\n</code></pre>\n\n<p>This base class will probably have default methods such as:</p>\n\n<ul>\n<li>Feed</li>\n<li>Mate</li>\n</ul>\n\n<p>All of which are behavior that have more or less the same implementation between either species. To define this you will have:</p>\n\n<pre class="lang-cs prettyprint-override"><code>public class Dog : Mammal\npublic class Cat : Mammal\n</code></pre>\n\n<p>Now let\'s suppose there are other mammals, which we will usually see in a zoo:</p>\n\n<pre class="lang-cs prettyprint-override"><code>public class Giraffe : Mammal\npublic class Rhinoceros : Mammal\npublic class Hippopotamus : Mammal\n</code></pre>\n\n<p>This will still be valid because at the core of the functionality <code>Feed()</code> and <code>Mate()</code> will still be the same.</p>\n\n<p>However, giraffes, rhinoceros, and hippos are not exactly animals that you can make pets out of. That\'s where an interface will be useful:</p>\n\n<pre class="lang-cs prettyprint-override"><code>public interface IPettable\n{\n    IList&lt;Trick&gt; Tricks{get; set;}\n    void Bathe();\n    void Train(Trick t);\n}\n</code></pre>\n\n<p>The implementation for the above contract will not be the same between a cat and dog; putting their implementations in an abstract class to inherit will be a bad idea. </p>\n\n<p>Your Dog and Cat definitions should now look like:</p>\n\n<pre class="lang-cs prettyprint-override"><code>public class Dog : Mammal, IPettable\npublic class Cat : Mammal, IPettable\n</code></pre>\n\n<p>Theoretically you can override them from a higher base class, but essentially an interface allows you to add on only the things you need into a class without the need for inheritance.</p>\n\n<p>Consequently, because you can usually only inherit from one abstract class (in most statically typed OO languages that is... exceptions include C++) but be able to implement multiple interfaces, it allows you to construct objects in a strictly <em>as required</em> basis.</p>\n'}, {'answer_id': 56961, 'author': 'Gishu', 'author_id': 1695, 'author_profile': 'https://Stackoverflow.com/users/1695', 'pm_score': 6, 'selected': False, 'text': "<h2>Interfaces</h2>\n<ul>\n<li>Most languages allow you to implement multiple interfaces</li>\n<li>Modifying an interface is a breaking change. All implementations need to be recompiled/modified.</li>\n<li>All members are public. Implementations have to implement all members.</li>\n<li>Interfaces help in Decoupling. You can use mock frameworks to mock out anything behind an interface</li>\n<li>Interfaces normally indicate a kind of behavior</li>\n<li>Interface implementations are decoupled / isolated from each other</li>\n</ul>\n<h2>Base classes</h2>\n<ul>\n<li>Allows you to add some <strong>default</strong> implementation that you get for free by derivation (From C# 8.0 by interface you can have default implementation)</li>\n<li>Except C++, you can only derive from one class. Even if could from multiple classes, it is usually a bad idea.</li>\n<li>Changing the base class is relatively easy. Derivations do not need to do anything special</li>\n<li>Base classes can declare protected and public functions that can be accessed by derivations</li>\n<li>Abstract Base classes can't be mocked easily like interfaces</li>\n<li>Base classes normally indicate type hierarchy (IS A)</li>\n<li>Class derivations may come to depend on some base behavior (have intricate knowledge of parent implementation). Things can be messy if you make a change to the base implementation for one guy and break the others.</li>\n</ul>\n"}, {'answer_id': 57027, 'author': 'fryguybob', 'author_id': 4592, 'author_profile': 'https://Stackoverflow.com/users/4592', 'pm_score': 6, 'selected': False, 'text': "<p>This is pretty .NET specific, but the Framework Design Guidelines book argues that in general classes give more flexibility in an evolving framework.  Once an interface is shipped, you don't get the chance to change it without breaking code that used that interface.  With a class however, you can modify it and not break code that links to it. As long you make the right modifications, which includes adding new functionality, you will be able to extend and evolve your code.</p>\n\n<p>Krzysztof Cwalina says on page 81:</p>\n\n<blockquote>\n  <p>Over the course of the three versions of the .NET Framework, I have talked about this guideline with quite a few developers on our team.  Many of them, including those who initially disagreed with the guidelines, have said that they regret having shipped some API as an interface.  I have not heard of even one case in which somebody regretted that they shipped a class.</p>\n</blockquote>\n\n<p>That being said there certainly is a place for interfaces.  As a general guideline always provide an abstract base class implementation of an interface if for nothing else as an example of a way to implement the interface.  In the best case that base class will save a lot of work.</p>\n"}, {'answer_id': 57271, 'author': 'Aaron Fischer', 'author_id': 5618, 'author_profile': 'https://Stackoverflow.com/users/5618', 'pm_score': 1, 'selected': False, 'text': '<p>An inheritor of a base class should have an "is a" relationship.  Interface represents An "implements a" relationship.\nSo only use a base class when your inheritors will maintain the is a relationship.</p>\n'}, {'answer_id': 57316, 'author': 'David Pokluda', 'author_id': 223, 'author_profile': 'https://Stackoverflow.com/users/223', 'pm_score': 0, 'selected': False, 'text': '<p>Use your own judgement and be smart. Don\'t always do what others (like me) are saying. You will hear "prefer interfaces to abstract classes" but it really depends. It depends what the class is.</p>\n\n<p>In the above mentioned case where we have a hierarchy of objects, interface is a good idea. Interface helps to work with collections of these objects and it also helps when implementing a service working with any object of the hierarchy. You just define a contract for working with objects from the hierarchy.</p>\n\n<p>On the other hand when you implement a bunch of services that share a common functionality you can either separate the common functionality into a complete separate class or you can move it up into a common base class and make it abstract so that nobody can instantiate the base class.</p>\n\n<p>Also consider this how to support your abstractions over time. Interfaces are fixed: You release an interface as a contract for a set of functionality that any type can implement. Base classes can be extended over time. Those extensions become part of every derived class.</p>\n'}, {'answer_id': 57349, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': "<p>I recommend using composition instead of inheritence whenever possible.  Use interfaces but use member objects for base implementation.  That way, you can define a factory that constructs your objects to behave in a certain way.  If you want to change the behavior then you make a new factory method (or abstract factory) that creates different types of sub-objects.</p>\n\n<p>In some cases, you may find that your primary objects don't need interfaces at all, if all of the mutable behavior is defined in helper objects.</p>\n\n<p>So instead of IPet or PetBase, you might end up with a Pet which has an IFurBehavior parameter.  The IFurBehavior parameter is set by the CreateDog() method of the PetFactory.  It is this parameter which is called for the shed() method.</p>\n\n<p>If you do this you'll find your code is much more flexible and most of your simple objects deal with very basic system-wide behaviors.</p>\n\n<p>I recommend this pattern even in multiple-inheritence languages.</p>\n"}, {'answer_id': 57457, 'author': 'Mark', 'author_id': 5904, 'author_profile': 'https://Stackoverflow.com/users/5904', 'pm_score': 0, 'selected': False, 'text': '<p>Interfaces have the distinct advantage of being somewhat "hot swappable" for classes.  Changing a class from one parent to another will often result in a great deal of work, but Interfaces can often be removed and changed without a great deal of effect on the implementation class.  This is especially useful in cases where you have several narrow sets of behaviour that you "may" want a class to implement.</p>\n\n<p>This works especially well in my field: game programming.  Base classes can get bloated with tons of behaviours that "may" be needed by inherited objects.  With interfaces different behaviours can be added or removed to objects easily and readily.  For example, if I create an interface for "IDamageEffects" for objects that I want to reflect damage, then I can easily apply that to various game objects, and easily change my mind later.  Say I design an initial class that I want to use for "static" decorative objects and I initially decide they are non-destructible.  Later on, I may decide it would be more fun if they could blow up so I alter the class to implement the "IDamageEffects" interface.  This is much easier to do than switching base classes or creating a new object hierarchy.</p>\n'}, {'answer_id': 57464, 'author': 'Keithius', 'author_id': 5956, 'author_profile': 'https://Stackoverflow.com/users/5956', 'pm_score': 0, 'selected': False, 'text': '<p>There are other advantages to inheritance as well - such as the ability for a variable to be able to hold an object of either the parent class or the inherited class (without having to declare it as something generic, like "Object"). </p>\n\n<p>For example, in .NET WinForms, most UI components derive from System.Windows.Forms.Control, so a variable declared as that could "hold" just about any UI element - be it a button, a ListView, or what have you. Now, granted, you won\'t have access to all the properties or methods of the item, but you\'ll have all the basic stuff - and that can be useful.</p>\n'}, {'answer_id': 57714, 'author': 'Flory', 'author_id': 5551, 'author_profile': 'https://Stackoverflow.com/users/5551', 'pm_score': 4, 'selected': False, 'text': "<p>Juan,</p>\n\n<p>I like to think of interfaces as a way to characterize a class.  A particular dog breed class, say a YorkshireTerrier, may be a descended of the parent dog class, but it is also implements IFurry, IStubby, and IYippieDog.  So the class defines what the class is but the interface tells us things about it.</p>\n\n<p>The advantage of this is it allows me to, for example, gather all the IYippieDog's and throw them into my Ocean collection.  So now I can reach across a particular set of objects and find ones that meet the criteria I am looking at without inspecting the class too closely.</p>\n\n<p>I find that interfaces really should define a sub-set of the public behavior of a class.  If it defines all the public behavior for all the classes that implement then it usually does not need to exist.  They do not tell me anything useful.</p>\n\n<p>This thought though goes counter to the idea that every class should have an interface and you should code to the interface.  That's fine, but you end up with a lot of one to one interfaces to classes and it makes things confusing.  I understand that the idea is it does not really cost anything to do and now you can swap things in and out with ease.  However, I find that I rarely do that.  Most of the time I am just modifying the existing class in place and have the exact same issues I always did if the public interface of that class needs changing, except I now have to change it in two places.</p>\n\n<p>So if you think like me you would definitely say that Cat and Dog are IPettable.  It is a characterization that matches them both.</p>\n\n<p>The other piece of this though is should they have the same base class?  The question is do they need to be broadly treated as the same thing.  Certainly they are both Animals, but does that fit how we are going to use them together.  </p>\n\n<p>Say I want to gather all Animal classes and put them in my Ark container.</p>\n\n<p>Or do they need to be Mammals?  Perhaps we need some kind of cross animal milking factory?</p>\n\n<p>Do they even need to be linked together at all?  Is it enough to just know they are both IPettable?</p>\n\n<p>I often feel the desire to derive a whole class hierarchy when I really just need one class.   I do it in anticipation someday I might need it and usually I never do.  Even when I do, I usually find I have to do a lot to fix it.  That’s because the first class I am creating is not the Dog, I am not that lucky, it is instead the Platypus.  Now my entire class hierarchy is based on the bizarre case and I have a lot of wasted code. </p>\n\n<p>You might also find at some point that not all Cats are IPettable (like that hairless one).  Now you can move that Interface to all the derivative classes that fit.  You will find that a much less breaking change that all of a sudden Cats are no longer derived from PettableBase.</p>\n"}, {'answer_id': 57763, 'author': 'Scott Lawrence', 'author_id': 3475, 'author_profile': 'https://Stackoverflow.com/users/3475', 'pm_score': 2, 'selected': False, 'text': "<p>Previous comments about using abstract classes for common implementation is definitely on the mark.  One benefit I haven't seen mentioned yet is that the use of interfaces makes it much easier to implement mock objects for the purpose of unit testing.  Defining IPet and PetBase as Jason Cohen described enables you to mock different data conditions easily, without the overhead of a physical database (until you decide it's time to test the real thing).</p>\n"}, {'answer_id': 59999, 'author': 'theschmitzer', 'author_id': 2167252, 'author_profile': 'https://Stackoverflow.com/users/2167252', 'pm_score': 2, 'selected': False, 'text': '<p>Don\'t use a base class unless you know what it means, and that it applies in this case.  If it applies, use it, otherwise, use interfaces.  But note the answer about small interfaces.</p>\n\n<p>Public Inheritance is overused in OOD and expresses a lot more than most developers realize or are willing to live up to.  See the <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" rel="nofollow noreferrer">Liskov Substitutablity Principle</a></p>\n\n<p>In short, if A "is a" B then A requires no more than B and delivers no less than B, for every method it exposes.</p>\n'}, {'answer_id': 60013, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 0, 'selected': False, 'text': '<p>You should use a base class if there really isn\'t any reason for other developers to desire using their own base class in addition to your type\'s members <strong>and</strong> you foresee versioning issues (see <a href="http://haacked.com/archive/2008/02/21/versioning-issues-with-abstract-base-classes-and-interfaces.aspx" rel="nofollow noreferrer">http://haacked.com/archive/2008/02/21/versioning-issues-with-abstract-base-classes-and-interfaces.aspx</a>).</p>\n\n<p>If inheriting developers have any reason to use their own base class to implement your type\'s interface and you don\'t see the interface changing, then go with an interface. In this case, you can still throw in a default base class that implements the interface for sake of convenience.</p>\n'}, {'answer_id': 65660, 'author': 'Sijin', 'author_id': 8884, 'author_profile': 'https://Stackoverflow.com/users/8884', 'pm_score': 4, 'selected': False, 'text': '<p>Also keep in mind not to get swept away in OO (<a href="http://www.indiangeek.net/2006/10/25/do-not-start-with-an-interface" rel="noreferrer">see blog</a>) and always model objects based on behavior required, if you were designing an app where the only behavior you required was a generic name and species for an animal then you would only need one class Animal with a property for the name, instead of millions of classes for every possible animal in the world.</p>\n'}, {'answer_id': 65939, 'author': 'Thomas Danecker', 'author_id': 9632, 'author_profile': 'https://Stackoverflow.com/users/9632', 'pm_score': 7, 'selected': False, 'text': '<p>Interfaces and base classes represent two different forms of relationships.</p>\n\n<p><strong>Inheritance</strong> (base classes) represent an "is-a" relationship. E.g. a dog or a cat "is-a" pet. This relationship always represents the (single) <strong>purpose</strong> of the class (in conjunction with the <a href="http://codebetter.com/blogs/glenn.block/archive/2008/09/11/the-alt-net-criterion.aspx" rel="noreferrer" title="References of the most important principles of software engineering">"single responsibility principle"</a>).</p>\n\n<p><strong>Interfaces</strong>, on the other hand, represent <strong>additional features</strong> of a class. I\'d call it an "is" relationship, like in "<code>Foo</code> is disposable", hence the <code>IDisposable</code> interface in C#.</p>\n'}, {'answer_id': 67653, 'author': 'Wheat', 'author_id': 70142, 'author_profile': 'https://Stackoverflow.com/users/70142', 'pm_score': 2, 'selected': False, 'text': '<p>Conceptually, an <em>interface</em> is used to formally and semi-formally define a set of methods that an object will provide. Formally means a set of method names and signatures, and semi-formally means human readable documentation associated with those methods.</p>\n\n<p>Interfaces are only descriptions of an API (after all, <a href="https://en.wikipedia.org/wiki/Application_programming_interface" rel="nofollow noreferrer">API</a> stands for application programming <strong>interface</strong>), they can\'t contain any implementation, and it\'s not possible to use or run an interface. They only make explicit the contract of how you should interact with an object.</p>\n\n<p>Classes provide an implementation, and they can declare that they implement zero, one or more Interfaces. If a <em>class</em> is intended to be inherited, the convention is to prefix the class name with "Base".</p>\n\n<p>There is a distinction between a <em>base class</em> and an <em>abstract base classes</em> (ABC). ABCs mix interface and implementation together. Abstract outside of computer programming means "summary", that is "abstract == interface". An <em>abstract base class</em> can then describe both an interface, as well as an empty, partial or complete implementation that is intended to be inherited.</p>\n\n<p>Opinions on when to use <em>interfaces</em> versus <em>abstract base classes</em> versus just <em>classes</em> is going to vary wildly based on both what you are developing, and which language you are developing in. Interfaces are often associated only with statically typed languages such as Java or C#, but dynamically typed languages can also have <em>interfaces</em> and <em>abstract base classes</em>. In Python for example, the distinction is made clear between a Class, which declares that it <strong>implements</strong> an <em>interface</em>, and an object, which is an instance of a <em>class</em>, and is said to <strong>provide</strong> that <em>interface</em>. It\'s possible in a dynamic language that two objects that are both instances of the same <em>class</em>, can declare that they provide completely <strong>different</strong> interfaces. In Python this is only possible for object attributes, while methods are shared state between all objects of a <em>class</em>. However, in Ruby, objects can have per-instance methods, so it\'s possible that the <em>interface</em> between two objects of the same <em>class</em> can vary as much as the programmer desires (however, Ruby doesn\'t have any explicit way of declaring Interfaces).</p>\n\n<p>In dynamic languages the interface to an object is often implicitly assumed, either by introspecting an object and asking it what methods it provides (<em>look before you leap</em>) or preferably by simply attempting to use the desired <em>interface</em> on an object and catching exceptions if the object doesn\'t provide that <em>interface</em> (<em>easier to ask forgiveness than permission</em>). This can lead to "false positives" where two <em>interfaces</em> have the same method name, but are semantically different. However, the trade-off is that your code is more flexible since you don\'t need to over specify up-front to anticipate all possible uses of your code.</p>\n'}, {'answer_id': 203853, 'author': 'RWendi', 'author_id': 15152, 'author_profile': 'https://Stackoverflow.com/users/15152', 'pm_score': 4, 'selected': False, 'text': '<p>Here is the basic and simple definiton of interface and base class:</p>\n\n<ul>\n<li>Base class = object inheritance.</li>\n<li>Interface = functional inheritance.</li>\n</ul>\n\n<p>cheers</p>\n'}, {'answer_id': 210208, 'author': 'Richard Harrison', 'author_id': 19624, 'author_profile': 'https://Stackoverflow.com/users/19624', 'pm_score': 4, 'selected': False, 'text': '<p>It is explained well in this <a href="http://www.javaworld.com/javaworld/javaqa/2001-04/03-qa-0420-abstract.html" rel="nofollow noreferrer">Java World article</a>.</p>\n\n<p>Personally, I tend to use interfaces to define interfaces - i.e. parts of the system design that specify how something should be accessed.</p>\n\n<p>It\'s not uncommon that I will have a class implementing one or more interfaces.</p>\n\n<p>Abstract classes I use as a basis for something else.</p>\n\n<p>The following is an extract from the above mentioned article <a href="http://www.javaworld.com/javaworld/javaqa/2001-04/03-qa-0420-abstract.html" rel="nofollow noreferrer">JavaWorld.com article, author Tony Sintes, 04/20/01</a></p>\n\n<hr/>\n\n<blockquote>\n  <h2>Interface vs. abstract class</h2>\n  \n  <p>Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks.</p>\n  \n  <p>Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn\'t know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, Java calls the method defined by the child class.</p>\n  \n  <p>Many developers forget that a class that defines an abstract method can call that method as well. Abstract classes are an excellent way to create planned inheritance hierarchies. They\'re also a good choice for nonleaf classes in class hierarchies.</p>\n  \n  <h2>Class vs. interface</h2>\n</blockquote>\n\n<p>Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme. I use interfaces when I see that something in my design will change frequently.</p>\n\n<blockquote>\n  <p>For example, the Strategy pattern lets you swap new algorithms and processes into your program without altering the objects that use them. A media player might know how to play CDs, MP3s, and wav files. Of course, you don\'t want to hardcode those playback algorithms into the player; that will make it difficult to add a new format like AVI. Furthermore, your code will be littered with useless case statements. And to add insult to injury, you will need to update those case statements each time you add a new algorithm. All in all, this is not a very object-oriented way to program.</p>\n  \n  <p>With the Strategy pattern, you can simply encapsulate the algorithm behind an object. If you do that, you can provide new media plug-ins at any time. Let\'s call the plug-in class MediaStrategy. That object would have one method: playStream(Stream s). So to add a new algorithm, we simply extend our algorithm class. Now, when the program encounters the new media type, it simply delegates the playing of the stream to our media strategy. Of course, you\'ll need some plumbing to properly instantiate the algorithm strategies you will need.</p>\n  \n  <p>This is an excellent place to use an interface. We\'ve used the Strategy pattern, which clearly indicates a place in the design that will change. Thus, you should define the strategy as an interface. You should generally favor interfaces over inheritance when you want an object to have a certain type; in this case, MediaStrategy. Relying on inheritance for type identity is dangerous; it locks you into a particular inheritance hierarchy. Java doesn\'t allow multiple inheritance, so you can\'t extend something that gives you a useful implementation or more type identity.</p>\n</blockquote>\n'}, {'answer_id': 260213, 'author': 'Parappa', 'author_id': 9974, 'author_profile': 'https://Stackoverflow.com/users/9974', 'pm_score': 2, 'selected': False, 'text': '<p>Another option to keep in mind is using the "has-a" relationship, aka "is implemented in terms of" or "composition."  Sometimes this is a cleaner, more flexible way to structure things than using "is-a" inheritance.</p>\n\n<p>It may not make as much sense logically to say that Dog and Cat both "have" a Pet, but it avoids common multiple inheritance pitfalls:</p>\n\n<pre><code>public class Pet\n{\n    void Bathe();\n    void Train(Trick t);\n}\n\npublic class Dog\n{\n    private Pet pet;\n\n    public void Bathe() { pet.Bathe(); }\n    public void Train(Trick t) { pet.Train(t); }\n}\n\npublic class Cat\n{\n    private Pet pet;\n\n    public void Bathe() { pet.Bathe(); }\n    public void Train(Trick t) { pet.Train(t); }\n}\n</code></pre>\n\n<p>Yes, this example shows that there is a lot of code duplication and lack of elegance involved in doing things this way.  But one should also appreciate that this helps to keep Dog and Cat decoupled from the Pet class (in that Dog and Cat do not have access to the private members of Pet), and it leaves room for Dog and Cat to inherit from something else--possibly the Mammal class.</p>\n\n<p>Composition is preferable when no private access is required and you don\'t need to refer to Dog and Cat using generic Pet references/pointers.  Interfaces give you that generic reference capability and can help cut down on the verbosity of your code, but they can also obfuscate things when they are poorly organized.  Inheritance is useful when you need private member access, and in using it you are committing yourself to highly coupling your Dog and Cat classes to your Pet class, which is a steep cost to pay.</p>\n\n<p>Between inheritance, composition, and interfaces there is no one way that is always right, and it helps to consider how all three options can be used in harmony.  Of the three, inheritance is typically the option that should be used the least often.</p>\n'}, {'answer_id': 300019, 'author': 'YeahStu', 'author_id': 1300, 'author_profile': 'https://Stackoverflow.com/users/1300', 'pm_score': 3, 'selected': False, 'text': '<p>The case for Base Classes over Interfaces was explained well in the Submain .NET Coding Guidelines:</p>\n\n<blockquote>\n  <p><strong>Base Classes vs. Interfaces</strong> \n  An interface type is a partial\n  description of a value, potentially\n  supported by many object types. Use\n  base classes instead of interfaces\n  whenever possible. From a versioning\n  perspective, classes are more flexible\n  than interfaces. With a class, you can\n  ship Version 1.0 and then in Version\n  2.0 add a new method to the class. As long as the method is not abstract,\n  any existing derived classes continue\n  to function unchanged.</p>\n  \n  <p>Because interfaces do not support\n  implementation inheritance, the\n  pattern that applies to classes does\n  not apply to interfaces. Adding a\n  method to an interface is equivalent\n  to adding an abstract method to a base\n  class; any class that implements the\n  interface will break because the class\n  does not implement the new method.\n  Interfaces are appropriate in the\n  following situations:</p>\n  \n  <ol>\n  <li>Several unrelated classes want to support the protocol.</li>\n  <li>These classes already have established base classes (for\n  example,\n  some are user interface (UI) controls,\n  and some are XML Web services).</li>\n  <li>Aggregation is not appropriate or practicable. In all other\n  situations,\n  class inheritance is a better model.</li>\n  </ol>\n</blockquote>\n'}, {'answer_id': 361188, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>When I first started learning about object-oriented programming, I made the easy and probably common mistake of using inheritance to share common behavior - even where that behavior was not essential to the nature of the object.</p>\n\n<p>To further build on an example much used in this particular question, there are <em>lots</em> of things that are petable - girlfriends, cars, fuzzy blankets... - so I might have had a Petable class that provided this common behavior, and various classes inheriting from it.</p>\n\n<p>However, being petable is not part of the nature of any of these objects. There are vastly more important concepts that <em>are</em> essential to their nature - the girlfriend is a person, the car is a land vehicle, the cat is a mammal...</p>\n\n<p>Behaviors should be assigned first to interfaces (including the default interface of the class), and promoted to a base class only if they are (a) common to a large group of classes that are subsets of a larger class - in the same sense that "cat" and "person" are subsets of "mammal".</p>\n\n<p>The catch is, after you understand object-oriented design sufficiently better than I did at first, you\'ll normally do this automatically without even thinking about it. So the bare truth of the statement "code to an interface, not an abstract class" becomes so obvious you have a hard time believing anyone would bother to say it - and start trying to read other meanings into it.</p>\n\n<p>Another thing I\'d add is that if a class is <em>purely</em> abstract - with no non-abstract, non-inherited members or methods exposed to child, parent, or client - then why is it a class? It could be replaced, in some cases by an interface and in other cases by Null.</p>\n'}, {'answer_id': 5090489, 'author': 'Phil C', 'author_id': 388267, 'author_profile': 'https://Stackoverflow.com/users/388267', 'pm_score': 2, 'selected': False, 'text': '<p>Regarding C#, in some senses interfaces and abstract classes can be interchangeable. However, the differences are: i) interfaces cannot implement code; ii) because of this, interfaces cannot call further up the stack to subclass; and iii) only can abstract class may be inherited on a class, whereas multiple interfaces may be implemented on a class.</p>\n'}, {'answer_id': 5304755, 'author': 'sunwukung', 'author_id': 124192, 'author_profile': 'https://Stackoverflow.com/users/124192', 'pm_score': 1, 'selected': False, 'text': '<p>Use Interfaces to enforce a contract ACROSS families of unrelated classes. For example, you might have common access methods for classes that represent collections, but contain radically different data i.e. one class might represent a result set from a query, while the other might represent the images in a gallery. Also, you can implement multiple interfaces, thus allowing you to blend (and signify) the capabilities of the class.</p>\n\n<p>Use Inheritance when the classes bear a common relationship and therefore have a similair structural and behavioural signature, i.e. Car, Motorbike, Truck and SUV are all types of road vehicle that might contain a number of wheels, a top speed</p>\n'}, {'answer_id': 12880702, 'author': 'Akhil Jain', 'author_id': 1225413, 'author_profile': 'https://Stackoverflow.com/users/1225413', 'pm_score': 3, 'selected': False, 'text': '<p>I have a rough rule-of-thumb</p>\n\n<p><strong>Functionality:</strong> likely to be different in all parts: Interface.</p>\n\n<p><strong>Data, and functionality, parts will be mostly the same, parts different:</strong> abstract class.</p>\n\n<p><strong>Data, and functionality, actually working, if extended only with slight changes:</strong> ordinary (concrete) class</p>\n\n<p><strong>Data and functionality, no changes planned:</strong> ordinary (concrete) class with final modifier.</p>\n\n<p><strong>Data, and maybe functionality: read-only:</strong> enum members.</p>\n\n<p>This is very rough and ready and not at all strictly defined, but there is a spectrum from interfaces where everything is intended to be changed to enums where everything is fixed a bit like a read-only file.</p>\n'}, {'answer_id': 25577574, 'author': 'x19', 'author_id': 1817640, 'author_profile': 'https://Stackoverflow.com/users/1817640', 'pm_score': 0, 'selected': False, 'text': '<p>Thanks for <a href="https://stackoverflow.com/a/56912/1817640">answering</a> by <a href="https://stackoverflow.com/users/372/jon-limjap">Jon Limjap</a> but I want to add some explanation for concept of Interface and Abstract Base Classes</p>\n\n<p><strong>Interface Types vs. Abstract Base Classes</strong></p>\n\n<p>Adapted from the <a href="http://www.apress.com/9781430242338" rel="nofollow noreferrer">Pro C# 5.0 and the .NET 4.5 Framework</a> book.</p>\n\n<p>The interface type might seem very similar to an abstract base class. Recall\nthat when a class is marked as abstract, it may define any number of abstract members to provide a\npolymorphic interface to all derived types. However, even when a class does define a set of abstract\nmembers, it is also free to define any number of constructors, field data, nonabstract members (with\nimplementation), and so on. Interfaces, on the other hand, contain only abstract member definitions.\nThe polymorphic interface established by an abstract parent class suffers from one major limitation\nin that only derived types support the members defined by the abstract parent. However, in larger\nsoftware systems, it is very common to develop multiple class hierarchies that have no common parent\nbeyond System.Object. Given that abstract members in an abstract base class apply only to derived\ntypes, we have no way to configure types in different hierarchies to support the same polymorphic\ninterface. By way of example, assume you have defined the following abstract class:</p>\n\n<pre><code>public abstract class CloneableType\n{\n// Only derived types can support this\n// "polymorphic interface." Classes in other\n// hierarchies have no access to this abstract\n// member.\n   public abstract object Clone();\n}\n</code></pre>\n\n<p>Given this definition, only members that extend CloneableType are able to support the Clone()\nmethod. If you create a new set of classes that do not extend this base class, you can’t gain this\npolymorphic interface. Also, you might recall that C# does not support multiple inheritance for classes.\nTherefore, if you wanted to create a MiniVan that is-a Car and is-a CloneableType, you are unable to do so:</p>\n\n<pre><code>// Nope! Multiple inheritance is not possible in C#\n// for classes.\npublic class MiniVan : Car, CloneableType\n{\n}\n</code></pre>\n\n<p>As you would guess, interface types come to the rescue. After an interface has been defined, it can\nbe implemented by any class or structure, in any hierarchy, within any namespace or any assembly\n(written in any .NET programming language). As you can see, interfaces are highly polymorphic.\nConsider the standard .NET interface named ICloneable, defined in the System namespace. This\ninterface defines a single method named Clone():</p>\n\n<pre><code>public interface ICloneable\n{\nobject Clone();\n}\n</code></pre>\n'}, {'answer_id': 25996970, 'author': 'Ganesh Kodiganti', 'author_id': 3452366, 'author_profile': 'https://Stackoverflow.com/users/3452366', 'pm_score': 2, 'selected': False, 'text': '<p>By def, interface provides a layer to communicate with other code. All the public properties and methods of a class are by default implementing implicit interface. We can also define an interface as a role, when ever any class needs to play that role, it has to implement it giving it different forms of implementation depending on the class implementing it. Hence when you talk about interface, you are talking about polymorphism and when you are talking about base class, you are talking about inheritance.  Two concepts of oops !!!</p>\n'}, {'answer_id': 27388452, 'author': 'Jason Roell', 'author_id': 1253072, 'author_profile': 'https://Stackoverflow.com/users/1253072', 'pm_score': 3, 'selected': False, 'text': '<p><strong>Source</strong>: <a href="http://jasonroell.com/2014/12/09/interfaces-vs-abstract-classes-what-should-you-use/" rel="noreferrer">http://jasonroell.com/2014/12/09/interfaces-vs-abstract-classes-what-should-you-use/</a></p>\n\n<p>C# is a wonderful language that has matured and evolved over the last 14 years. This is great for us developers because a mature language provides us with a plethora of language features that are at our disposal.</p>\n\n<p>However, with much power becomes much responsibility. Some of these features can be misused, or sometimes it is hard to understand why you would choose to use one feature over another. Over the years, a feature that I have seen many developers struggle with is when to choose to use an interface or to choose to use an abstract class. Both have there advantages and disadvantages and the correct time and place to use each. But how to we decide???</p>\n\n<p>Both provide for reuse of common functionality between types. The most obvious difference right away is that interfaces provide no implementation for their functionality whereas abstract classes allow you to implement some “base” or “default” behavior and then have the ability to “override” this default behavior with the classes derived types if necessary.</p>\n\n<p>This is all well and good and provides for great reuse of code and adheres to the DRY (Don’t Repeat Yourself) principle of software development. Abstract classes are great to use when you have an “is a” relationship.</p>\n\n<p>For example: A golden retriever “is a” type of dog. So is a poodle. They both can bark, as all dogs can. However, you might want to state that the poodle park is significantly different than the “default” dog bark. Therefor, it could make sense for you to implement something as follows:</p>\n\n<pre><code>public abstract class Dog\n{\n      public virtual void Bark()\n      {\n        Console.WriteLine("Base Class implementation of Bark");\n      }\n}\n\npublic class GoldenRetriever : Dog\n{\n   // the Bark method is inherited from the Dog class\n}\n\npublic class Poodle : Dog\n{\n  // here we are overriding the base functionality of Bark with our new implementation\n  // specific to the Poodle class\n  public override void Bark()\n  {\n     Console.WriteLine("Poodle\'s implementation of Bark");\n  }\n}\n\n// Add a list of dogs to a collection and call the bark method.\n\nvoid Main()\n{\n    var poodle = new Poodle();\n    var goldenRetriever = new GoldenRetriever();\n\n    var dogs = new List&lt;Dog&gt;();\n    dogs.Add(poodle);\n    dogs.Add(goldenRetriever);\n\n    foreach (var dog in dogs)\n    {\n       dog.Bark();\n    }\n}\n\n// Output will be:\n// Poodle\'s implementation of Bark\n// Base Class implementation of Bark\n\n// \n</code></pre>\n\n<p>As you can see, this would be a great way to keep your code DRY and allow for the base class implementation be called when any of the types can just rely on the default Bark instead of a special case implementation. The classes like GoldenRetriever, Boxer, Lab could all could inherit the “default” (bass class) Bark at no charge just because they implement the Dog abstract class.</p>\n\n<p>But I’m sure you already knew that.</p>\n\n<p>You are here because you want to understand why you might want to choose an interface over an abstract class or vice versa. Well one reason you may want to choose an interface over an abstract class is when you don’t have or want to prevent a default implementation. This is usually because the types that are implementing the interface not related in an “is a” relationship. Actually, they don’t have to be related at all except for the fact that each type “is able” or has “the ablity” to do something or have something.</p>\n\n<p>Now what the heck does that mean? Well, for example: A human is not a duck…and a duck is not a human. Pretty obvious. However, both a duck and a human have “the ability” to swim (given that the human passed his swimming lessons in 1st grade :) ). Also, since a duck is not a human or vice versa, this is not an “is a” realationship, but instead an “is able” relationship and we can use an interface to illustrate that:</p>\n\n<pre><code>// Create ISwimable interface\npublic interface ISwimable\n{\n      public void Swim();\n}\n\n// Have Human implement ISwimable Interface\npublic class Human : ISwimable\n\n     public void Swim()\n     {\n        //Human\'s implementation of Swim\n        Console.WriteLine("I\'m a human swimming!");\n     }\n\n// Have Duck implement ISwimable interface\npublic class Duck: ISwimable\n{\n     public void Swim()\n     {\n          // Duck\'s implementation of Swim\n          Console.WriteLine("Quack! Quack! I\'m a Duck swimming!")\n     }\n}\n\n//Now they can both be used in places where you just need an object that has the ability "to swim"\n\npublic void ShowHowYouSwim(ISwimable somethingThatCanSwim)\n{\n     somethingThatCanSwim.Swim();\n}\n\npublic void Main()\n{\n      var human = new Human();\n      var duck = new Duck();\n\n      var listOfThingsThatCanSwim = new List&lt;ISwimable&gt;();\n\n      listOfThingsThatCanSwim.Add(duck);\n      listOfThingsThatCanSwim.Add(human);\n\n      foreach (var something in listOfThingsThatCanSwim)\n      {\n           ShowHowYouSwim(something);\n      }\n}\n\n // So at runtime the correct implementation of something.Swim() will be called\n // Output:\n // Quack! Quack! I\'m a Duck swimming!\n // I\'m a human swimming!\n</code></pre>\n\n<p>Using interfaces like the code above will allow you to pass an object into a method that “is able” to do something.  The code doesn’t care how it does it…All it knows is that it can call the Swim method on that object and that object will know which behavior take at run-time based on its type.</p>\n\n<p>Once again, this helps your code stay DRY so that you would not have to write multiple methods that are calling the object to preform the same core function (ShowHowHumanSwims(human), ShowHowDuckSwims(duck), etc.)</p>\n\n<p>Using an interface here allows the calling methods to not have to worry about what type is which or how the behavior is implemented. It just knows that given the interface, each object will have to have implemented the Swim method so it is safe to call it in its own code and allow the behavior of the Swim method be handled within its own class.</p>\n\n<p>Summary:</p>\n\n<p>So my main rule of thumb is use an abstract class when you want to implement a “default” functionality for a class hierarchy or/and the classes or types you are working with share a “is a” relationship (ex. poodle “is a” type of dog).</p>\n\n<p>On the other hand use an interface when you do not have an “is a” relationship but have types that share “the ability” to do something or have something (ex. Duck “is not” a human. However, duck and human share “the ability” to swim).</p>\n\n<p>Another difference to note between abstract classes and interfaces is that a class can implement one to many interfaces but a class can only inherit from ONE abstract class (or any class for that matter). Yes, you can nest classes and have an inheritance hierarchy (which many programs do and should have) but you cannot inherit two classes in one derived class definition (this rule applies to C#. In some other languages you are able to do this, usually only because of the lack of interfaces in these languages).</p>\n\n<p>Also remember when using interfaces to adhere to the Interface Segregation Principle (ISP). ISP states that no client should be forced to depend on methods it does not use. For this reason interfaces should be focused on specific tasks and are usually very small (ex. IDisposable, IComparable ).</p>\n\n<p>Another tip is if you are developing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.</p>\n\n<p>Hope this clears things up for some people!</p>\n\n<p>Also if you can think of any better examples or want to point something out, please do so in the comments below!</p>\n'}, {'answer_id': 28104375, 'author': 'dSerk', 'author_id': 2158635, 'author_profile': 'https://Stackoverflow.com/users/2158635', 'pm_score': 1, 'selected': False, 'text': '<p>Make a list of the things your objects <em>must</em> be, have, or do and the things your objects <em>can</em> (or <em>might</em>) be, have, or do. <em>Must</em> indicates your base types and <em>can</em> indicates your interfaces. </p>\n\n<p>E.g., your PetBase <em>must</em> Breathe, and your IPet <em>might</em> DoTricks.</p>\n\n<p>Analysis of your problem domain will help you define the precise hierarchy structure.</p>\n'}, {'answer_id': 34608857, 'author': 'Ravindra babu', 'author_id': 4999394, 'author_profile': 'https://Stackoverflow.com/users/4999394', 'pm_score': 1, 'selected': False, 'text': '<blockquote>\n  <p>When should I use an interface and when should I use a base class?</p>\n</blockquote>\n\n<p>You should use interface if </p>\n\n<ol>\n<li>You have pure <code>abstract</code> methods and don\'t have non-abstract methods</li>\n<li>You don\'t have default implementation of <code>non abstract</code> methods (except for Java 8 language, where interface methods provides default implementation)</li>\n<li>If you are using Java 8, now interface will provide default implementation for some non-abstract methods. This will make <code>interface</code> more usable compared to <code>abstract</code> classes.</li>\n</ol>\n\n<p>Have a look at this SE <a href="https://stackoverflow.com/questions/479142/when-to-use-an-interface-instead-of-an-abstract-class-and-vice-versa/33963465#33963465">question</a> for more details. </p>\n\n<blockquote>\n  <p>Should it always be an interface if I don\'t want to actually define a base implementation of the methods?</p>\n</blockquote>\n\n<p>Yes. It\'s better and cleaner. Even if you have a base class with some abstract methods, let\'s base class extends <code>abstract</code> methods through interface. You can change interface in future without changing the base class.</p>\n\n<p>Example in java: </p>\n\n<pre><code>abstract class PetBase implements IPet {\n// Add all abstract methods in IPet interface and keep base class clean. \n   Base class will contain only non abstract methods and static methods.\n}\n</code></pre>\n\n<blockquote>\n  <p>If I have a Dog and Cat class. Why would I want to implement IPet instead of PetBase? I can understand having interfaces for ISheds or IBarks (IMakesNoise?), because those can be placed on a pet by pet basis, but I don\'t understand which to use for a generic Pet.</p>\n</blockquote>\n\n<p>I prefer to have base class implement the interface.</p>\n\n<pre><code> abstract class PetBase implements IPet {\n // Add all abstract methods in IPet\n }\n\n /*If ISheds,IBarks is common for Pets, your PetBase can implement ISheds,IBarks. \n  Respective implementations of PetBase can change the behaviour in their concrete classes*/\n\n abstract class PetBase implements IPet,ISheds,IBarks {\n // Add all abstract methods in respective interfaces\n }\n</code></pre>\n\n<p><strong>Advantages:</strong></p>\n\n<ol>\n<li><p>If I want to add one more abstract method in existing interfaces, I simple change interface without touching the abstract base class. If I want to change the contract, I will change interface &amp; implementation classes without touching base class. </p></li>\n<li><p>You can provide immutability to base class through interface. Have a look at this <a href="http://www.andygibson.net/blog/programming/immutability-through-interfaces/" rel="nofollow noreferrer">article</a></p></li>\n</ol>\n\n<p>Refer to this related SE question for more details:</p>\n\n<p><a href="https://stackoverflow.com/questions/18777989/how-should-i-have-explained-the-difference-between-an-interface-and-an-abstract/34978606#34978606">How should I have explained the difference between an Interface and an Abstract class?</a></p>\n'}, {'answer_id': 35669282, 'author': 'Jaimin Patel', 'author_id': 3396808, 'author_profile': 'https://Stackoverflow.com/users/3396808', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Prefer interfaces over abstract classes</strong></p>\n\n<p>Rationale,\nthe main points to consider [two already mentioned here] are :</p>\n\n<ul>\n<li>Interfaces are more flexible, because a class can implement multiple\ninterfaces.  Since Java does not have multiple inheritance, using\nabstract classes prevents your users from using any other class\nhierarchy. <strong>In general, prefer interfaces when there are no default\nimplementations or state.</strong> Java collections offer good examples of\nthis (Map, Set, etc.).</li>\n<li>Abstract classes have the advantage of allowing better forward\ncompatibility.  Once clients use an interface, you cannot change it;\nif they use an abstract class, you can still add behavior without\nbreaking existing code. <strong>If compatibility is a concern, consider using\nabstract classes.</strong></li>\n<li>Even if you do have default implementations or internal state,\n<strong>consider offering an interface and an abstract implementation of it</strong>.\nThis will assist clients, but still allow them greater freedom if\ndesired [1].<br>\nOf course, the subject has been discussed at length\nelsewhere [2,3].</li>\n</ul>\n\n<p>[1] It adds more code, of course, but if brevity is your primary concern, you probably should have avoided Java in the first place!</p>\n\n<p>[2] Joshua Bloch, Effective Java, items 16-18.</p>\n\n<p>[3] <a href="http://www.codeproject.com/KB/ar" rel="nofollow">http://www.codeproject.com/KB/ar</a>...</p>\n'}, {'answer_id': 35803354, 'author': 'Adam Hughes', 'author_id': 4076764, 'author_profile': 'https://Stackoverflow.com/users/4076764', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve found that a pattern of Interface > Abstract > Concrete works in the following use-case:</p>\n\n<pre><code>1.  You have a general interface (eg IPet)\n2.  You have a implementation that is less general (eg Mammal)\n3.  You have many concrete members (eg Cat, Dog, Ape)\n</code></pre>\n\n<p>The abstract class defines default shared attributes of the concrete classes, yet enforces the interface.  For example:</p>\n\n<pre><code>public interface IPet{\n\n    public boolean hasHair();\n\n    public boolean walksUprights();\n\n    public boolean hasNipples();\n}\n</code></pre>\n\n<p>Now, since all mammals have hair and nipples (AFAIK, I\'m not a zoologist), we can roll this into the abstract base class</p>\n\n<pre><code>public abstract class Mammal() implements IPet{\n\n     @override\n     public walksUpright(){\n         throw new NotSupportedException("Walks Upright not implemented");\n     }\n\n     @override\n     public hasNipples(){return true}\n\n     @override\n     public hasHair(){return true}\n</code></pre>\n\n<p>And then the concrete classes merely define that they walk upright.</p>\n\n<pre><code>public class Ape extends Mammal(){\n\n    @override\n    public walksUpright(return true)\n}\n\npublic class Catextends Mammal(){\n\n    @override\n    public walksUpright(return false)\n}\n</code></pre>\n\n<p>This design is nice when there are lots of concrete classes, and you don\'t want to maintain boilerplate just to program to an interface.  If new methods were added to the interface, it would break all of the resulting classes, so you are still getting the advantages of the interface approach.</p>\n\n<p><strong>In this case, the abstract could just as well be concrete; however, the abstract designation helps to emphasize that this pattern is being employed.</strong></p>\n'}]
['https://Stackoverflow.com/questions/56867', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2871/']