Why can't I seem to grasp interfaces? - oop
Could someone please demystify interfaces for me or point me to some good examples? I keep seeing interfaces popup here and there, but I haven't ever really been exposed to good explanations of interfaces or when to use them.
I am talking about interfaces in a context of interfaces vs. abstract classes.
Interfaces allow you to program against a "description" instead of a type, which allows you to more-loosely associate elements of your software.
Think of it this way: You want to share data with someone in the cube next to you, so you pull out your flash stick and copy/paste. You walk next door and the guy says "is that USB?" and you say yes - all set. It doesn't matter the size of the flash stick, nor the maker - all that matters is that it's USB.
In the same way, interfaces allow you to generisize your development. Using another analogy - imagine you wanted to create an application that virtually painted cars. You might have a signature like this:
public void Paint(Car car, System.Drawing.Color color)...
This would work until your client said "now I want to paint trucks" so you could do this:
public void Paint (Vehicle vehicle, System.Drawing.Color color)...
this would broaden your app... until your client said "now I want to paint houses!" What you could have done from the very beginning is created an interface:
public interface IPaintable{
void Paint(System.Drawing.Color color);
}
...and passed that to your routine:
public void Paint(IPaintable item, System.Drawing.Color color){
item.Paint(color);
}
Hopefully this makes sense - it's a pretty simplistic explanation but hopefully gets to the heart of it.
Interfaces establish a contract between a class and the code that calls it. They also allow you to have similar classes that implement the same interface but do different actions or events and not have to know which you are actually working with. This might make more sense as an example so let me try one here.
Say you have a couple classes called Dog, Cat, and Mouse. Each of these classes is a Pet and in theory you could inherit them all from another class called Pet but here's the problem. Pets in and of themselves don't do anything. You can't go to the store and buy a pet. You can go and buy a dog or a cat but a pet is an abstract concept and not concrete.
So You know pets can do certain things. They can sleep, or eat, etc. So you define an interface called IPet and it looks something like this (C# syntax)
public interface IPet
{
void Eat(object food);
void Sleep(int duration);
}
Each of your Dog, Cat, and Mouse classes implement IPet.
public class Dog : IPet
So now each of those classes has to have it's own implementation of Eat and Sleep. Yay you have a contract... Now what's the point.
Next let's say you want to make a new object called PetStore. And this isn't a very good PetStore so they basically just sell you a random pet (yes i know this is a contrived example).
public class PetStore
{
public static IPet GetRandomPet()
{
//Code to return a random Dog, Cat, or Mouse
}
}
IPet myNewRandomPet = PetStore.GetRandomPet();
myNewRandomPet.Sleep(10);
The problem is you don't know what type of pet it will be. Thanks to the interface though you know whatever it is it will Eat and Sleep.
So this answer may not have been helpful at all but the general idea is that interfaces let you do neat stuff like Dependency Injection and Inversion of Control where you can get an object, have a well defined list of stuff that object can do without ever REALLY knowing what the concrete type of that object is.
The easiest answer is that interfaces define a what your class can do. It's a "contract" that says that your class will be able to do that action.
Public Interface IRollOver
Sub RollOver()
End Interface
Public Class Dog Implements IRollOver
Public Sub RollOver() Implements IRollOver.RollOver
Console.WriteLine("Rolling Over!")
End Sub
End Class
Public Sub Main()
Dim d as New Dog()
Dim ro as IRollOver = TryCast(d, IRollOver)
If ro isNot Nothing Then
ro.RollOver()
End If
End Sub
Basically, you are guaranteeing that the Dog class always has the ability to roll over as long as it continues to implement that Interface. Should cats ever gain the ability to RollOver(), they too could implement that interface, and you can treat both Dogs and Cats homogeneously when asking them to RollOver().
When you drive a friend's car, you more or less know how to do that. This is because conventional cars all have a very similar interface: steering wheel, pedals, and so forth. Think of this interface as a contract between car manufacturers and drivers. As a driver (the user/client of the interface in software terms), you don't need to learn the particulars of different cars to be able to drive them: e.g., all you need to know is that turning the steering wheel makes the car turn. As a car manufacturer (the provider of an implementation of the interface in software terms) you have a clear idea what your new car should have and how it should behave so that drivers can use them without much extra training. This contract is what people in software design refer to as decoupling (the user from the provider) -- the client code is in terms of using an interface rather than a particular implementation thereof and hence doesn't need to know the details of the objects implementing the interface.
Interfaces are a mechanism to reduce coupling between different, possibly disparate parts of a system.
From a .NET perspective
The interface definition is a list of operations and/or properties.
Interface methods are always public.
The interface itself doesn't have to be public.
When you create a class that implements the interface, you must provide either an explicit or implicit implementation of all methods and properties defined by the interface.
Further, .NET has only single inheritance, and interfaces are a necessity for an object to expose methods to other objects that aren't aware of, or lie outside of its class hierarchy. This is also known as exposing behaviors.
An example that's a little more concrete:
Consider is we have many DTO's (data transfer objects) that have properties for who updated last, and when that was. The problem is that not all the DTO's have this property because it's not always relevant.
At the same time we desire a generic mechanism to guarantee these properties are set if available when submitted to the workflow, but the workflow object should be loosely coupled from the submitted objects. i.e. the submit workflow method shouldn't really know about all the subtleties of each object, and all objects in the workflow aren't necessarily DTO objects.
// First pass - not maintainable
void SubmitToWorkflow(object o, User u)
{
if (o is StreetMap)
{
var map = (StreetMap)o;
map.LastUpdated = DateTime.UtcNow;
map.UpdatedByUser = u.UserID;
}
else if (o is Person)
{
var person = (Person)o;
person.LastUpdated = DateTime.Now; // Whoops .. should be UtcNow
person.UpdatedByUser = u.UserID;
}
// Whoa - very unmaintainable.
In the code above, SubmitToWorkflow() must know about each and every object. Additionally, the code is a mess with one massive if/else/switch, violates the don't repeat yourself (DRY) principle, and requires developers to remember copy/paste changes every time a new object is added to the system.
// Second pass - brittle
void SubmitToWorkflow(object o, User u)
{
if (o is DTOBase)
{
DTOBase dto = (DTOBase)o;
dto.LastUpdated = DateTime.UtcNow;
dto.UpdatedByUser = u.UserID;
}
It is slightly better, but it is still brittle. If we want to submit other types of objects, we need still need more case statements. etc.
// Third pass pass - also brittle
void SubmitToWorkflow(DTOBase dto, User u)
{
dto.LastUpdated = DateTime.UtcNow;
dto.UpdatedByUser = u.UserID;
It is still brittle, and both methods impose the constraint that all the DTOs have to implement this property which we indicated wasn't universally applicable. Some developers might be tempted to write do-nothing methods, but that smells bad. We don't want classes pretending they support update tracking but don't.
Interfaces, how can they help?
If we define a very simple interface:
public interface IUpdateTracked
{
DateTime LastUpdated { get; set; }
int UpdatedByUser { get; set; }
}
Any class that needs this automatic update tracking can implement the interface.
public class SomeDTO : IUpdateTracked
{
// IUpdateTracked implementation as well as other methods for SomeDTO
}
The workflow method can be made to be a lot more generic, smaller, and more maintainable, and it will continue to work no matter how many classes implement the interface (DTOs or otherwise) because it only deals with the interface.
void SubmitToWorkflow(object o, User u)
{
IUpdateTracked updateTracked = o as IUpdateTracked;
if (updateTracked != null)
{
updateTracked.LastUpdated = DateTime.UtcNow;
updateTracked.UpdatedByUser = u.UserID;
}
// ...
We can note the variation void SubmitToWorkflow(IUpdateTracked updateTracked, User u) would guarantee type safety, however it doesn't seem as relevant in these circumstances.
In some production code we use, we have code generation to create these DTO classes from the database definition. The only thing the developer does is have to create the field name correctly and decorate the class with the interface. As long as the properties are called LastUpdated and UpdatedByUser, it just works.
Maybe you're asking What happens if my database is legacy and that's not possible? You just have to do a little more typing; another great feature of interfaces is they can allow you to create a bridge between the classes.
In the code below we have a fictitious LegacyDTO, a pre-existing object having similarly-named fields. It's implementing the IUpdateTracked interface to bridge the existing, but differently named properties.
// Using an interface to bridge properties
public class LegacyDTO : IUpdateTracked
{
public int LegacyUserID { get; set; }
public DateTime LastSaved { get; set; }
public int UpdatedByUser
{
get { return LegacyUserID; }
set { LegacyUserID = value; }
}
public DateTime LastUpdated
{
get { return LastSaved; }
set { LastSaved = value; }
}
}
You might thing Cool, but isn't it confusing having multiple properties? or What happens if there are already those properties, but they mean something else? .NET gives you the ability to explicitly implement the interface.
What this means is that the IUpdateTracked properties will only be visible when we're using a reference to IUpdateTracked. Note how there is no public modifier on the declaration, and the declaration includes the interface name.
// Explicit implementation of an interface
public class YetAnotherObject : IUpdatable
{
int IUpdatable.UpdatedByUser
{ ... }
DateTime IUpdatable.LastUpdated
{ ... }
Having so much flexibility to define how the class implements the interface gives the developer a lot of freedom to decouple the object from methods that consume it. Interfaces are a great way to break coupling.
There is a lot more to interfaces than just this. This is just a simplified real-life example that utilizes one aspect of interface based programming.
As I mentioned earlier, and by other responders, you can create methods that take and/or return interface references rather than a specific class reference. If I needed to find duplicates in a list, I could write a method that takes and returns an IList (an interface defining operations that work on lists) and I'm not constrained to a concrete collection class.
// Decouples the caller and the code as both
// operate only on IList, and are free to swap
// out the concrete collection.
public IList<T> FindDuplicates( IList<T> list )
{
var duplicates = new List<T>()
// TODO - write some code to detect duplicate items
return duplicates;
}
Versioning caveat
If it's a public interface, you're declaring I guarantee interface x looks like this! And once you have shipped code and published the interface, you should never change it. As soon as consumer code starts to rely on that interface, you don't want to break their code in the field.
See this Haacked post for a good discussion.
Interfaces versus abstract (base) classes
Abstract classes can provide implementation whereas Interfaces cannot. Abstract classes are in some ways more flexible in the versioning aspect if you follow some guidelines like the NVPI (Non-Virtual Public Interface) pattern.
It's worth reiterating that in .NET, a class can only inherit from a single class, but a class can implement as many interfaces as it likes.
Dependency Injection
The quick summary of interfaces and dependency injection (DI) is that the use of interfaces enables developers to write code that is programmed against an interface to provide services. In practice you can end up with a lot of small interfaces and small classes, and one idea is that small classes that do one thing and only one thing are much easier to code and maintain.
class AnnualRaiseAdjuster
: ISalaryAdjuster
{
AnnualRaiseAdjuster(IPayGradeDetermination payGradeDetermination) { ... }
void AdjustSalary(Staff s)
{
var payGrade = payGradeDetermination.Determine(s);
s.Salary = s.Salary * 1.01 + payGrade.Bonus;
}
}
In brief, the benefit shown in the above snippet is that the pay grade determination is just injected into the annual raise adjuster. How pay grade is determined doesn't actually matter to this class. When testing, the developer can mock pay grade determination results to ensure the salary adjuster functions as desired. The tests are also fast because the test is only testing the class, and not everything else.
This isn't a DI primer though as there are whole books devoted to the subject; the above example is very simplified.
This is a rather "long" subject, but let me try to put it simple.
An interface is -as "they name it"- a Contract. But forget about that word.
The best way to understand them is through some sort of pseudo-code example. That's how I understood them long time ago.
Suppose you have an app that processes Messages. A Message contains some stuff, like a subject, a text, etc.
So you write your MessageController to read a database, and extract messages. It's very nice until you suddenly hear that Faxes will be also implemented soon. So you will now have to read "Faxes" and process them as messages!
This could easily turn into a Spagetti code. So what you do instead of having a MessageController than controls "Messages" only, you make it able to work with an interface called IMessage (the I is just common usage, but not required).
Your IMessage interface, contains some basic data you need to make sure that you're able to process the Message as such.
So when you create your EMail, Fax, PhoneCall classes, you make them Implement the Interface called IMessage.
So in your MessageController, you can have a method called like this:
private void ProcessMessage(IMessage oneMessage)
{
DoSomething();
}
If you had not used Interfaces, you'd have to have:
private void ProcessEmail(Email someEmail);
private void ProcessFax(Fax someFax);
etc.
So, by using a common interface, you just made sure that the ProcessMessage method will be able to work with it, no matter if it was a Fax, an Email a PhoneCall, etc.
Why or how?
Because the interface is a contract that specifies some things you must adhere (or implement) in order to be able to use it. Think of it as a badge. If your object "Fax" doesn't have the IMessage interface, then your ProcessMessage method wouldn't be able to work with that, it will give you an invalid type, because you're passing a Fax to a method that expects an IMessage object.
Do you see the point?
Think of the interface as a "subset" of methods and properties that you will have available, despite the real object type. If the original object (Fax, Email, PhoneCall, etc) implements that interface, you can safety pass it across methods that need that Interface.
There's more magic hidden in there, you can CAST the interfaces back to their original objects:
Fax myFax = (Fax)SomeIMessageThatIReceive;
The ArrayList() in .NET 1.1 had a nice interface called IList. If you had an IList (very "generic") you could transform it into an ArrayList:
ArrayList ar = (ArrayList)SomeIList;
And there are thousands of samples out there in the wild.
Interfaces like ISortable, IComparable, etc., define the methods and properties you must implement in your class in order to achieve that functionality.
To expand our sample, you could have a List<> of Emails, Fax, PhoneCall, all in the same List, if the Type is IMessage, but you couldn't have them all together if the objects were simply Email, Fax, etc.
If you wanted to sort (or enumerate for example) your objects, you'd need them to implement the corresponding interface. In the .NET sample, if you have a list of "Fax" objects and want to be able to sort them by using MyList.Sort(), you need to make your fax class like this:
public class Fax : ISorteable
{
//implement the ISorteable stuff here.
}
I hope this gives you a hint. Other users will possibly post other good examples. Good luck! and Embrace the power of INterfaces.
warning: Not everything is good about interfaces, there are some issues with them, OOP purists will start a war on this. I shall remain aside. One drawback of an Interfce (in .NET 2.0 at least) is that you cannot have PRIVATE members, or protected, it must be public. This makes some sense, but sometimes you wish you could simply declare stuff as private or protected.
In addition to the function interfaces have within programming languages, they also are a powerful semantic tool when expressing design ideas to other people.
A code base with well-designed interfaces is suddenly a lot easier to discuss. "Yes, you need a CredentialsManager to register new remote servers." "Pass a PropertyMap to ThingFactory to get a working instance."
Ability to address a complex thing with a single word is pretty useful.
Interfaces let you code against objects in a generic way. For instance, say you have a method that sends out reports. Now say you have a new requirement that comes in where you need to write a new report. It would be nice if you could reuse the method you already had written right? Interfaces makes that easy:
interface IReport
{
string RenderReport();
}
class MyNewReport : IReport
{
public string RenderReport()
{
return "Hello World Report!";
}
}
class AnotherReport : IReport
{
public string RenderReport()
{
return "Another Report!";
}
}
//This class can process any report that implements IReport!
class ReportEmailer()
{
public void EmailReport(IReport report)
{
Email(report.RenderReport());
}
}
class MyApp()
{
void Main()
{
//create specific "MyNewReport" report using interface
IReport newReport = new MyNewReport();
//create specific "AnotherReport" report using interface
IReport anotherReport = new AnotherReport();
ReportEmailer reportEmailer = new ReportEmailer();
//emailer expects interface
reportEmailer.EmailReport(newReport);
reportEmailer.EmailReport(anotherReport);
}
}
Interfaces are also key to polymorphism, one of the "THREE PILLARS OF OOD".
Some people touched on it above, polymorphism just means a given class can take on different "forms". Meaning, if we have two classes, "Dog" and "Cat" and both implement the interface "INeedFreshFoodAndWater" (hehe) - your code can do something like this (pseudocode):
INeedFreshFoodAndWater[] array = new INeedFreshFoodAndWater[];
array.Add(new Dog());
array.Add(new Cat());
foreach(INeedFreshFoodAndWater item in array)
{
item.Feed();
item.Water();
}
This is powerful because it allows you to treat different classes of objects abstractly, and allows you to do things like make your objects more loosely coupled, etc.
OK, so it's about abstract classes vs. interfaces...
Conceptually, abstract classes are there to be used as base classes. Quite often they themselves already provide some basic functionality, and the subclasses have to provide their own implementation of the abstract methods (those are the methods which aren't implemented in the abstract base class).
Interfaces are mostly used for decoupling the client code from the details of a particular implementation. Also, sometimes the ability to switch the implementation without changing the client code makes the client code more generic.
On the technical level, it's harder to draw the line between abstract classes and interfaces, because in some languages (e.g., C++), there's no syntactic difference, or because you could also use abstract classes for the purposes of decoupling or generalization. Using an abstract class as an interface is possible because every base class, by definition, defines an interface that all of its subclasses should honor (i.e., it should be possible to use a subclass instead of a base class).
Interfaces are a way to enforce that an object implements a certain amount of functionality, without having to use inheritance (which leads to strongly coupled code, instead of loosely coupled which can be achieved through using interfaces).
Interfaces describe the functionality, not the implementation.
Most of the interfaces you come across are a collection of method and property signatures. Any one who implements an interface must provide definitions to what ever is in the interface.
Simply put: An interface is a class that methods defined but no implementation in them. In contrast an abstract class has some of the methods implemented but not all.
Think of an interface as a contract. When a class implements an interface, it is essentially agreeing to honor the terms of that contract. As a consumer, you only care that the objects you have can perform their contractual duties. Their inner workings and details aren't important.
One good reason for using an interface vs. an abstract class in Java is that a subclass cannot extend multiple base classes, but it CAN implement multiple interfaces.
Java does not allow multiple inheritance (for very good reasons, look up dreadful diamond) but what if you want to have your class supply several sets of behavior? Say you want anyone who uses it to know it can be serialized, and also that it can paint itself on the screen. the answer is to implement two different interfaces.
Because interfaces contain no implementation of their own and no instance members it is safe to implement several of them in the same class with no ambiguities.
The down side is that you will have to have the implementation in each class separately. So if your hierarchy is simple and there are parts of the implementation that should be the same for all the inheriting classes use an abstract class.
Assuming you're referring to interfaces in statically-typed object-oriented languages, the primary use is in asserting that your class follows a particular contract or protocol.
Say you have:
public interface ICommand
{
void Execute();
}
public class PrintSomething : ICommand
{
OutputStream Stream { get; set; }
String Content {get; set;}
void Execute()
{
Stream.Write(content);
}
}
Now you have a substitutable command structure. Any instance of a class that implements IExecute can be stored in a list of some sort, say something that implements IEnumerable and you can loop through that and execute each one, knowing that each object will Just Do The Right Thing. You can create a composite command by implementing CompositeCommand which will have its own list of commands to run, or a LoopingCommand to run a set of commands repeatedly, then you'll have most of a simple interpreter.
When you can reduce a set of objects to a behavior that they all have in common, you might have cause to extract an interface. Also, sometimes you can use interfaces to prevent objects from accidentally intruding on the concerns of that class; for example, you may implement an interface that only allows clients to retrieve, rather than change data in your object, and have most objects receive only a reference to the retrieval interface.
Interfaces work best when your interfaces are relatively simple and make few assumptions.
Look up the Liskov subsitution principle to make more sense of this.
Some statically-typed languages like C++ don't support interfaces as a first-class concept, so you create interfaces using pure abstract classes.
Update
Since you seem to be asking about abstract classes vs. interfaces, here's my preferred oversimplification:
Interfaces define capabilities and features.
Abstract classes define core functionality.
Typically, I do an extract interface refactoring before I build an abstract class. I'm more likely to build an abstract class if I think there should be a creational contract (specifically, that a specific type of constructor should always be supported by subclasses). However, I rarely use "pure" abstract classes in C#/java. I'm far more likely to implement a class with at least one method containing meaningful behavior, and use abstract methods to support template methods called by that method. Then the abstract class is a base implementation of a behavior, which all concrete subclasses can take advantage of without having to reimplement.
Simple answer: An interface is a bunch of method signatures (+ return type). When an object says it implements an interface, you know it exposes that set of methods.
Interfaces are a way to implement conventions in a way that is still strongly typed and polymorphic.
A good real world example would be IDisposable in .NET. A class that implements the IDisposable interface forces that class to implement the Dispose() method. If the class doesn't implement Dispose() you'll get a compiler error when trying to build. Additionally, this code pattern:
using (DisposableClass myClass = new DisposableClass())
{
// code goes here
}
Will cause myClass.Dispose() to be executed automatically when execution exits the inner block.
However, and this is important, there is no enforcement as to what your Dispose() method should do. You could have your Dispose() method pick random recipes from a file and email them to a distribution list, the compiler doesn't care. The intent of the IDisposable pattern is to make cleaning up resources easier. If instances of a class will hold onto file handles then IDisposable makes it very easy to centralize the deallocation and cleanup code in one spot and to promote a style of use which ensures that deallocation always occurs.
And that's the key to interfaces. They are a way to streamline programming conventions and design patterns. Which, when used correctly, promotes simpler, self-documenting code which is easier to use, easier to maintain, and more correct.
Here is a db related example I often use. Let us say you have an object and a container object like an list. Let us assume that sometime you might want to store the objects in a particular sequence. Assume that the sequence is not related to the position in the array but instead that the objects are a subset of a larger set of objects and the sequence position is related to the database sql filtering.
To keep track of your customized sequence positions you could make your object implement a custom interface. The custom interface could mediate the organizational effort required to maintain such sequences.
For example, the sequence you are interested in has nothing to do with primary keys in the records. With the object implementing the interface you could say myObject.next() or myObject.prev().
I have had the same problem as you and I find the "contract" explanation a bit confusing.
If you specify that a method takes an IEnumerable interface as an in-parameter you could say that this is a contract specifying that the parameter must be of a type that inherits from the IEnumerable interface and hence supports all methods specified in the IEnumerable interface. The same would be true though if we used an abstract class or a normal class. Any object that inherits from those classes would be ok to pass in as a parameter. You would in any case be able to say that the inherited object supports all public methods in the base class whether the base class is a normal class, an abstract class or an interface.
An abstract class with all abstract methods is basically the same as an interface so you could say an interface is simply a class without implemented methods. You could actually drop interfaces from the language and just use abstract class with only abstract methods instead. I think the reason we separate them is for semantic reasons but for coding reasons I don't see the reason and find it just confusing.
Another suggestion could be to rename the interface to interface class as the interface is just another variation of a class.
In certain languages there are subtle differences that allows a class to inherit only 1 class but multiple interfaces while in others you could have many of both, but that is another issue and not directly related I think
The simplest way to understand interfaces is to start by considering what class inheritance means. It includes two aspects:
Members of a derived class can use public or protected members of a base class as their own.
Members of a derived class can be used by code which expects a member of the base class (meaning they are substitutable).
Both of these features are useful, but because it is difficult to allow a class to use members of more than one class as its own, many languages and frameworks only allow classes to inherit from a single base class. On the other hand, there is no particular difficulty with having a class be substitutable for multiple other unrelated things.
Further, because the first benefit of inheritance can be largely achieved via encapsulation, the relative benefit from allowing multiple-inheritance of the first type is somewhat limited. On the other hand, being able to substitute an object for multiple unrelated types of things is a useful ability which cannot be readily achieved without language support.
Interfaces provide a means by which a language/framework can allow programs to benefit from the second aspect of inheritance for multiple base types, without requiring it to also provide the first.
Interface is like a fully abstract class. That is, an abstract class with only abstract members. You can also implement multiple interfaces, it's like inheriting from multiple fully abstract classes. Anyway.. this explanation only helps if you understand what an abstract class is.
Like others have said here, interfaces define a contract (how the classes who use the interface will "look") and abstract classes define shared functionality.
Let's see if the code helps:
public interface IReport
{
void RenderReport(); // This just defines the method prototype
}
public abstract class Reporter
{
protected void DoSomething()
{
// This method is the same for every class that inherits from this class
}
}
public class ReportViolators : Reporter, IReport
{
public void RenderReport()
{
// Some kind of implementation specific to this class
}
}
public class ClientApp
{
var violatorsReport = new ReportViolators();
// The interface method
violatorsReport.RenderReport();
// The abstract class method
violatorsReport.DoSomething();
}
Interfaces require any class that implements them to contain the methods defined in the interface.
The purpose is so that, without having to see the code in a class, you can know if it can be used for a certain task. For example, the Integer class in Java implements the comparable interface, so, if you only saw the method header (public class String implements Comparable), you would know that it contains a compareTo() method.
In your simple case, you could achieve something similar to what you get with interfaces by using a common base class that implements show() (or perhaps defines it as abstract). Let me change your generic names to something more concrete, Eagle and Hawk instead of MyClass1 and MyClass2. In that case you could write code like
Bird bird = GetMeAnInstanceOfABird(someCriteriaForSelectingASpecificKindOfBird);
bird.Fly(Direction.South, Speed.CruisingSpeed);
That lets you write code that can handle anything that is a Bird. You could then write code that causes the Bird to do its thing (fly, eat, lay eggs, and so forth) that acts on an instance it treats as a Bird. That code would work whether Bird is really an Eagle, Hawk, or anything else that derives from Bird.
That paradigm starts to get messy, though, when you don't have a true is a relationship. Say you want to write code that flies things around in the sky. If you write that code to accept a Bird base class, it suddenly becomes hard to evolve that code to work on a JumboJet instance, because while a Bird and a JumboJet can certainly both fly, a JumboJet is most certainly not a Bird.
Enter the interface.
What Bird (and Eagle, and Hawk) do have in common is that they can all fly. If you write the above code instead to act on an interface, IFly, that code can be applied to anything that provides an implementation to that interface.
Related
Interface Segregation Principle and Convenience/Helper Methods
How does the Interface Segregation Principle apply to convenience/helper methods? For instance: I want to create an interface that represents business partners. The bare minimum that I would need would be a setter and a getter method that would set or get the entire list of partners: Interface Partners { method getList(); method setList(); } I also want to have a contains() method to tell me if a certain person was included in the list of partners. I consider this a helper or convenience method, because all it does it call getPartners() and then check if the given person is in that list. My understanding of the Interface Segregation Principle is that I should separate my contains() method into a separate interface, since someone might want to implement my Partners interface without providing an implementaiton for this unnecessary helper method. In my example, its not a big deal, but the list of helper methods can quickly grow long (addPartner, addPartnerByID, addPartnerByUserid, etc.), so this is a practical problem. My concern is that I'm finding it quite difficult to pick a name for an interface to hold my contains() method that does not sound cumbersome, and I think any time you have this much trouble naming something, it is a red flag that there is something wrong in your design. It does not seem right to have an interface named PartnersSupportingSetInclusionChecks, nor does it seem good to have an interface just named PartnerHelperMethods. How do I apply the Interface Segregation Principle to such methods?
since someone might want to implement my Partners interface without providing an implementation for this unnecessary helper method emphasis mine Please by all means have a contains() method if you think it's important to have in your API. Especially if all your client code currently use one. The Interface Segregation Principle is to keep totally unrelated methods out of the interface. It looks like you are trying to implement a Repository which should have a get, contains etc methods to see what elements are in the repository and a way to retrieve them. If you had other kinds of methods that had nothing to do with getting or setting Partners, then the ISP should be applied to make a different interface for that. However, you may want to think about separating your getting/contains methods from your setting/adding methods if you think you will have clients that treat this repository as read-only and should not be allowed to modify it, but you don't have to.
The following answer is based on C# language. It might not be valid in another language. I want to create an interface that represents business partners This first sentence tells me that you probably don´t need an interface, but a top-level abstract class. And it is very important to distinguish whether we need an interface or an abstract class. Abstract classes represent hierarchies, where each descendant of that hierarchy is a specialization, therefore you can adding more members in order to enrich the family. In this case, the relationship describes “This X is a Y” Interfaces represent a set of characteristics and behavior not linked to any hierarchy. Therefore, the main intention is to link different kind of classes that will have the same features or behaviors. The relationship describes “This X can do Y” So, assuming that what fits better with your description is an abstract class, I suggest the following: One option could be set the methods "getList()" and "setList()" as non-abstract methods and provide into the abstract class a field to store the list public abstract Partner { List<Partner> list; public void SetList(List<Partner> list) { list = list; } public List<Partner> GetList(Partner partner) { return list; } } So, the method "Contains" can be non-abstract aswell, so you don't force the descendant classes to provide an implementation. public bool Contains(Partner partner) { return list.Contains(partner); } And let's suppose that in the future you want to add new helpers methods. Those methods can be new non-abstract methods into the base class, so you will not affect your current descendants of "Partner". If you need to modify the implementation of helpers methods, you can set it as "virtual" so that the descendant classes can override the base implementation. public virtual void AddPartner(Partner partner) { list.Add(partner); }
Why are interfaces useful? (OOP)
I already know the fundamentals of the implements and interfaces. I don't understand when to use an interface. What is the requirement to have an interface? Example: /// Interface demo Interface IDemo { // Function prototype public void Show(); } // First class using the interface Class MyClass1 : IDemo { public void Show() { // Function body comes here Response.Write("I'm in MyClass"); } } // Second class using the interface Class MyClass2 : IDemo { public void Show() { // Function body comes here Response.Write("I'm in MyClass2"); Response.Write("So, what?"); } } These two classes have the same function name with different bodies. This can also be achieved without interfaces. What's the purpose of having the method reference? When I extend a superclass, at least I get the superclass's properties and methods. Please give me a clear explaining and a real world scenario for me to understand well.
First they provide a contract for users, so a user doesn't need to know what underlying implementation is used but rather just the contract. This creates loose coupling in case underlying implementation changes. Real World Examples In this manner we can use certain patterns like strategy and command pattern: Using a strategy pattern and a command pattern Real World Example of the Strategy Pattern Real world example of application of the command pattern Difference Between Abstract Class and Interface Much of this can be said about abstract classes, see here for the differences: Interface vs Abstract Class (general OO)
You need an interface if you need multiple inheritance. Suppose you have a class that needs to be Comparable and also a List. Since you can only inherit one class in some languages, in order to prove to the compiler that it has both Comparable's compareTo() method as well as List's add() method, you need interfaces. That's the very simplest explanation but I'm sure others will give more reasons. Also interfaces make multiple inheritance easier in some cases since there is nothing going on "in the background." they only specify what an object needs to offer in terms of methods.
Two reasons to use interfaces: You need multiple inheritance, and your programming language does not support it (e.g., Java, C#). In this case, most (all but one) of the base classes you inherit in your derived class will need to be defined as interface classes. You expect to use multiple implementations of a certain class. In this cases, the class can be an abstract class or an interface. Your client provides a specific concrete implementation of this class, which can vary from client to client. The interface (or abstract class) requires the same behavior (methods) for each implementation.
I believe one of the most inportant reasons for using interfaces is type matching. Your programe can be much more flixible by programming to an interface instead of an implementation. You could take a look at different design patterns (I suggest you start with Strategy Pattern, http://en.wikipedia.org/wiki/Strategy_pattern#Example) I reckon you will instantly understand how program to interfaces makes your code more flexible. Hope this can help.
Much of the power comes from the fact that an object can be referenced by a variable of the interface type. This is subtly vary powerful. private foo() { IDemo demoOne = new MyClass1(); IDemo demoTwo = new MyClass2(); } This can become vary powerful because you can encapsulate different behaviors. For example: private foo(bool option) { IDemo demo = option ? new MyClass1() : new MyClass2(); } private bar (IDemo demo) { demo.Show(); } Now bar can use the IDemo object without having to know which concrete implementation of IDemo is passed in. The decision about which implementation to use is encapsulated in the foo method. This might not seem like a big deal in such a simple example. If you look at the links posted in tigger's answer, you will see where this can become very useful. One case where this is particularly useful is with unit testing. You can have a business logic class that takes an interface to a data layer object. When the application runs, the business logic class is passed an instance of the real data layer object. When the class is unit tested, it is passed an instance of a object that returns test data. This allows the unit test to run with predictable data inputs. This is known at Dependency Injection. Another useful case is when you want to interact with framework or third-party code. Let's say you want to implement a custom collection. If your class implements the IEnumerable interface, you can iterate through the items in the collection in a foreach loop. The framework doesn't need to know how your class stores the items or what is in the items, but if it knows that you implemented IEnumerable, it can allow you to use a foreach loop.
When to implement an interface and when to extend a superclass?
I've been reading a lot about interfaces and class inheritance in Java, and I know how to do both and I think I have a good feel for both. But it seems that nobody ever really compares the two side by side and explains when and why you would want to use one or the other. I have not found a lot of times when implementing an interface would be a better system than extending a superclass. So when do you implement an interface and when do you extend a superclass?
Use an interface if you want to define a contract. I.e. X must take Y and return Z. It doesn't care how the code is doing that. A class can implement multiple interfaces. Use an abstract class if you want to define default behaviour in non-abstract methods so that the endusers can reuse it without rewriting it again and again. A class can extend from only one other class. An abstract class with only abstract methods can be as good definied as an interface. An abstract class without any abstract method is recognizeable as the Template Method pattern (see this answer for some real world examples). An abstract class in turn can perfectly implement an interface whenever you want to provide the enduser freedom in defining the default behaviour.
You should choose an interface if all you want is to define a contract i.e. method signatures that you want the inheriting classes to implement. An interface can have no implementation at all. The inheriting classes are free to choose their own implementation. Sometimes you want to define partial implementation in a base type and want to leave the rest to inheriting classes. If that is the case, choose an abstract class. An abstract class can define method implementations and variables while leaving some methods as abstract. Extending classes can choose how to implement the abstract methods while they also have the partial implementation provided by the superclass. One extreme of abstract classes is a pure abstract class - one that has only abstract methods and nothing else. If it comes to pure abstract class vs. an interface, go with the interface. Java allows only single implementation inheritance whereas it allows multiple interface inheritance meaning that a class can implement multiple interfaces but can extend only one class. So choosing a pure abstract class over the interface will mean that the subclass will not be allowed to extend any other class while implementing the abstract methods.
Use an interface to define behavior. User (abstract) classes (and subclasses) to provide implementation. They are not mutually exclusive; they can all work together. For example, lets say you are defining a data access object. You want your DAO to be able to load data. So put a load method on the interface. This means that anything that wants to call itself a DAO must implement load. Now lets say you need to load A and B. You can create a generic abstract class that is parameterized (generics) to provide the outline on how the load works. You then subclass that abstract class to provide the concrete implementations for A and B.
The main reason for using abstract classes and interfaces are different. An abstract class should be used when you have classes that have identical implementations for a bunch of methods, but vary in a few. This may be a bad example, but the most obvious use of abstract classes in the Java framework is within the java.io classes. OutputStream is just a stream of bytes. Where that stream goes to depends entirely on which subclass of OutputStream you're using... FileOutputStream, PipedOutputStream, the output stream created from a java.net.Socket's getOutputStream method... Note: java.io also uses the Decorator pattern to wrap streams in other streams/readers/writers. An interface should be used when you just want to guarantee that a class implements a set of methods, but you don't care how. The most obvious use of interfaces is within the Collections framework. I don't care how a List adds/removes elements, so long as I can call add(something) and get(0) to put and get elements. It may use an array (ArrayList, CopyOnWriteArrayList), linked list (LinkedList), etc... The other advantage in using interfaces is that a class may implement more than one. LinkedList is an implementation of both List and Deque.
No one? http://mindprod.com/jgloss/interfacevsabstract.html EDIT: I should supply more than a link Here's a situation. To build on the car example below, consider this interface Drivable { void drive(float miles); } abstract class Car implements Drivable { float gallonsOfGas; float odometer; final float mpg; protected Car(float mpg) { gallonsOfGas = 0; odometer = 0; this.mpg = mpg; } public void addGas(float gallons) { gallonsOfGas += gallons; } public void drive(float miles) { if(miles/mpg > gallonsOfGas) throw new NotEnoughGasException(); gallonsOfGas -= miles/mpg; odometer += miles; } } class LeakyCar extends Car { // still implements Drivable because of Car public addGas(float gallons) { super.addGas(gallons * .8); } // leaky tank } class ElectricCar extends Car { float electricMiles; public void drive(float miles) { // can we drive the whole way electric? if(electricMiles > miles) { electricMiles -= miles; odometer += miles; return; // early return here } if(electricMiles > 0) { // exhaust electric miles first if((miles-electricMiles)/mpg > gallonsOfGas) throw new NotEnoughGasException(); miles -= electricMiles; odometer += electricMiles; electricMiles = 0; } // finish driving super.drive(miles); } }
I think that interfaces work best when you use them to express that the object has a certain property or behavior, that spans multiple inheritance trees, and is only clearly defined for each class. For example think of Comparable. If you wanted to create a class Comparable to be extended by other classes, it would have to be very high on the inheritance tree, possible right after Object, and the property it expresses is that two objects of that type can be compared, but there's no way to define that generally (you can't have an implementation of compareTo directly in the Comparable class, it's different for every class that implements it). Classes work best when they define something clear, you know what properties and behaviors they have, and have actual implementations for methods, that you want to pass down to the children. So classes work when you need to define a concrete object like a human, or a car, and interfaces work better when you need more abstract behavior that's too general to belong to any inheritance tree, like the ability to be compared (Comparable) or to be run (Runnable).
One method of choosing between an interface and a base class is the consideration of code ownership. If you control all the code then a base class is a viable option. If on the other hand many different companies might want to produce replaceable components, that is define a contract then an interface is your only choice.
I found some articles, particularly some who describe why you should not use implementation inheritance (i.e. superclasses): Why extends is evil Inheritance of implementation is evil Implementation inheritance Implementation inheritance Java inheritance FAQ
I guess I'll give the classic car example. When you have a car interface, you can create a Ford, a Chevy, and an Oldsmobile. In other words, you create different kinds of cars from a car interface. When you have a car class, you can then extend the car class to make a truck, or a bus. In other words, you add new attributes to the sub classes while keeping the attributes of the base or super class.
You can think of extending from a super class if the derived class is of the same type.I mean that when a class extends an abstract class, they both should be of the same type, the only difference being that the super class has a more general behavior and the sub class has a more specific behavior. An interface is a totally different concept. When a class implements an interface, its either to expose some API(contract) or to get certain behavior. To give an example, I would say that Car is an abstract class. You can extend many classes from it like say Ford, Chevy and so on which are each of type car. But then if you need certain specific behavior like say you need a GPS in a car then the concrete class, eg Ford should implement GPS interface.
If you only want to inherit method signatures (name, arguments, return type) in the subclasses, use an interface, but if you also want to inherit implementation code, use a superclass.
What is the difference between an interface and abstract class?
What exactly is the difference between an interface and an abstract class?
Interfaces An interface is a contract: The person writing the interface says, "hey, I accept things looking that way", and the person using the interface says "OK, the class I write looks that way". An interface is an empty shell. There are only the signatures of the methods, which implies that the methods do not have a body. The interface can't do anything. It's just a pattern. For example (pseudo code): // I say all motor vehicles should look like this: interface MotorVehicle { void run(); int getFuel(); } // My team mate complies and writes vehicle looking that way class Car implements MotorVehicle { int fuel; void run() { print("Wrroooooooom"); } int getFuel() { return this.fuel; } } Implementing an interface consumes very little CPU, because it's not a class, just a bunch of names, and therefore there isn't any expensive look-up to do. It's great when it matters, such as in embedded devices. Abstract classes Abstract classes, unlike interfaces, are classes. They are more expensive to use, because there is a look-up to do when you inherit from them. Abstract classes look a lot like interfaces, but they have something more: You can define a behavior for them. It's more about a person saying, "these classes should look like that, and they have that in common, so fill in the blanks!". For example: // I say all motor vehicles should look like this: abstract class MotorVehicle { int fuel; // They ALL have fuel, so lets implement this for everybody. int getFuel() { return this.fuel; } // That can be very different, force them to provide their // own implementation. abstract void run(); } // My teammate complies and writes vehicle looking that way class Car extends MotorVehicle { void run() { print("Wrroooooooom"); } } Implementation While abstract classes and interfaces are supposed to be different concepts, the implementations make that statement sometimes untrue. Sometimes, they are not even what you think they are. In Java, this rule is strongly enforced, while in PHP, interfaces are abstract classes with no method declared. In Python, abstract classes are more a programming trick you can get from the ABC module and is actually using metaclasses, and therefore classes. And interfaces are more related to duck typing in this language and it's a mix between conventions and special methods that call descriptors (the __method__ methods). As usual with programming, there is theory, practice, and practice in another language :-)
The key technical differences between an abstract class and an interface are: Abstract classes can have constants, members, method stubs (methods without a body) and defined methods, whereas interfaces can only have constants and methods stubs. Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public (they are defined public by default). When inheriting an abstract class, a concrete child class must define the abstract methods, whereas an abstract class can extend another abstract class and abstract methods from the parent class don't have to be defined. Similarly, an interface extending another interface is not responsible for implementing methods from the parent interface. This is because interfaces cannot define any implementation. A child class can only extend a single class (abstract or concrete), whereas an interface can extend or a class can implement multiple other interfaces. A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility (public).
An Interface contains only the definition / signature of functionality, and if we have some common functionality as well as common signatures, then we need to use an abstract class. By using an abstract class, we can provide behavior as well as functionality both in the same time. Another developer inheriting abstract class can use this functionality easily, as they would only need to fill in the blanks. Taken from: http://www.dotnetbull.com/2011/11/difference-between-abstract-class-and.html http://www.dotnetbull.com/2011/11/what-is-abstract-class-in-c-net.html http://www.dotnetbull.com/2011/11/what-is-interface-in-c-net.html
An explanation can be found here: http://www.developer.com/lang/php/article.php/3604111/PHP-5-OOP-Interfaces-Abstract-Classes-and-the-Adapter-Pattern.htm An abstract class is a class that is only partially implemented by the programmer. It may contain one or more abstract methods. An abstract method is simply a function definition that serves to tell the programmer that the method must be implemented in a child class. An interface is similar to an abstract class; indeed interfaces occupy the same namespace as classes and abstract classes. For that reason, you cannot define an interface with the same name as a class. An interface is a fully abstract class; none of its methods are implemented and instead of a class sub-classing from it, it is said to implement that interface. Anyway I find this explanation of interfaces somewhat confusing. A more common definition is: An interface defines a contract that implementing classes must fulfill. An interface definition consists of signatures of public members, without any implementing code.
I don't want to highlight the differences, which have been already said in many answers ( regarding public static final modifiers for variables in interface & support for protected, private methods in abstract classes) In simple terms, I would like to say: interface: To implement a contract by multiple unrelated objects abstract class: To implement the same or different behaviour among multiple related objects From the Oracle documentation Consider using abstract classes if : You want to share code among several closely related classes. You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private). You want to declare non-static or non-final fields. Consider using interfaces if : You expect that unrelated classes would implement your interface. For example,many unrelated objects can implement Serializable interface. You want to specify the behaviour of a particular data type, but not concerned about who implements its behaviour. You want to take advantage of multiple inheritance of type. abstract class establishes "is a" relation with concrete classes. interface provides "has a" capability for classes. If you are looking for Java as programming language, here are a few more updates: Java 8 has reduced the gap between interface and abstract classes to some extent by providing a default method feature. An interface does not have an implementation for a method is no longer valid now. Refer to this documentation page for more details. Have a look at this SE question for code examples to understand better. How should I have explained the difference between an Interface and an Abstract class?
Some important differences: In the form of a table: As stated by Joe from javapapers: 1.Main difference is methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior. 2.Variables declared in a Java interface is by default final. An abstract class may contain non-final variables. 3.Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc.. 4.Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”. 5.An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces. 6.A Java class can implement multiple interfaces but it can extend only one abstract class. 7.Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists. 8.In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.
The main point is that: Abstract is object oriented. It offers the basic data an 'object' should have and/or functions it should be able to do. It is concerned with the object's basic characteristics: what it has and what it can do. Hence objects which inherit from the same abstract class share the basic characteristics (generalization). Interface is functionality oriented. It defines functionalities an object should have. Regardless what object it is, as long as it can do these functionalities, which are defined in the interface, it's fine. It ignores everything else. An object/class can contain several (groups of) functionalities; hence it is possible for a class to implement multiple interfaces.
When you want to provide polymorphic behaviour in an inheritance hierarchy, use abstract classes. When you want polymorphic behaviour for classes which are completely unrelated, use an interface.
I am constructing a building of 300 floors The building's blueprint interface For example, Servlet(I) Building constructed up to 200 floors - partially completed---abstract Partial implementation, for example, generic and HTTP servlet Building construction completed-concrete Full implementation, for example, own servlet Interface We don't know anything about implementation, just requirements. We can go for an interface. Every method is public and abstract by default It is a 100% pure abstract class If we declare public we cannot declare private and protected If we declare abstract we cannot declare final, static, synchronized, strictfp and native Every interface has public, static and final Serialization and transient is not applicable, because we can't create an instance for in interface Non-volatile because it is final Every variable is static When we declare a variable inside an interface we need to initialize variables while declaring Instance and static block not allowed Abstract Partial implementation It has an abstract method. An addition, it uses concrete No restriction for abstract class method modifiers No restriction for abstract class variable modifiers We cannot declare other modifiers except abstract No restriction to initialize variables Taken from DurgaJobs Website
Let's work on this question again: The first thing to let you know is that 1/1 and 1*1 results in the same, but it does not mean that multiplication and division are same. Obviously, they hold some good relationship, but mind you both are different. I will point out main differences, and the rest have already been explained: Abstract classes are useful for modeling a class hierarchy. At first glance of any requirement, we are partially clear on what exactly is to be built, but we know what to build. And so your abstract classes are your base classes. Interfaces are useful for letting other hierarchy or classes to know that what I am capable of doing. And when you say I am capable of something, you must have that capacity. Interfaces will mark it as compulsory for a class to implement the same functionalities.
If you have some common methods that can be used by multiple classes go for abstract classes. Else if you want the classes to follow some definite blueprint go for interfaces. Following examples demonstrate this. Abstract class in Java: abstract class Animals { // They all love to eat. So let's implement them for everybody void eat() { System.out.println("Eating..."); } // The make different sounds. They will provide their own implementation. abstract void sound(); } class Dog extends Animals { void sound() { System.out.println("Woof Woof"); } } class Cat extends Animals { void sound() { System.out.println("Meoww"); } } Following is an implementation of interface in Java: interface Shape { void display(); double area(); } class Rectangle implements Shape { int length, width; Rectangle(int length, int width) { this.length = length; this.width = width; } #Override public void display() { System.out.println("****\n* *\n* *\n****"); } #Override public double area() { return (double)(length*width); } } class Circle implements Shape { double pi = 3.14; int radius; Circle(int radius) { this.radius = radius; } #Override public void display() { System.out.println("O"); // :P } #Override public double area() { return (double)((pi*radius*radius)/2); } } Some Important Key points in a nutshell: The variables declared in Java interface are by default final. Abstract classes can have non-final variables. The variables declared in Java interface are by default static. Abstract classes can have non-static variables. Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..
It's pretty simple actually. You can think of an interface as a class which is only allowed to have abstract methods and nothing else. So an interface can only "declare" and not define the behavior you want the class to have. An abstract class allows you to do both declare (using abstract methods) as well as define (using full method implementations) the behavior you want the class to have. And a regular class only allows you to define, not declare, the behavior/actions you want the class to have. One last thing, In Java, you can implement multiple interfaces, but you can only extend one (Abstract Class or Class)... This means inheritance of defined behavior is restricted to only allow one per class... ie if you wanted a class that encapsulated behavior from Classes A,B&C you would need to do the following: Class A extends B, Class C extends A .. its a bit of a round about way to have multiple inheritance... Interfaces on the other hand, you could simply do: interface C implements A, B So in effect Java supports multiple inheritance only in "declared behavior" ie interfaces, and only single inheritance with defined behavior.. unless you do the round about way I described... Hopefully that makes sense.
The comparison of interface vs. abstract class is wrong. There should be two other comparisons instead: 1) interface vs. class and 2) abstract vs. final class. Interface vs Class Interface is a contract between two objects. E.g., I'm a Postman and you're a Package to deliver. I expect you to know your delivery address. When someone gives me a Package, it has to know its delivery address: interface Package { String address(); } Class is a group of objects that obey the contract. E.g., I'm a box from "Box" group and I obey the contract required by the Postman. At the same time I obey other contracts: class Box implements Package, Property { #Override String address() { return "5th Street, New York, NY"; } #Override Human owner() { // this method is part of another contract } } Abstract vs Final Abstract class is a group of incomplete objects. They can't be used, because they miss some parts. E.g., I'm an abstract GPS-aware box - I know how to check my position on the map: abstract class GpsBox implements Package { #Override public abstract String address(); protected Coordinates whereAmI() { // connect to GPS and return my current position } } This class, if inherited/extended by another class, can be very useful. But by itself - it is useless, since it can't have objects. Abstract classes can be building elements of final classes. Final class is a group of complete objects, which can be used, but can't be modified. They know exactly how to work and what to do. E.g., I'm a Box that always goes to the address specified during its construction: final class DirectBox implements Package { private final String to; public DirectBox(String addr) { this.to = addr; } #Override public String address() { return this.to; } } In most languages, like Java or C++, it is possible to have just a class, neither abstract nor final. Such a class can be inherited and can be instantiated. I don't think this is strictly in line with object-oriented paradigm, though. Again, comparing interfaces with abstract classes is not correct.
The only difference is that one can participate in multiple inheritance and other cannot. The definition of an interface has changed over time. Do you think an interface just has method declarations only and are just contracts? What about static final variables and what about default definitions after Java 8? Interfaces were introduced to Java because of the diamond problem with multiple inheritance and that's what they actually intend to do. Interfaces are the constructs that were created to get away with the multiple inheritance problem and can have abstract methods, default definitions and static final variables. See Why does Java allow static final variables in interfaces when they are only intended to be contracts?.
Interface: Turn ( Turn Left, Turn Right.) Abstract Class: Wheel. Class: Steering Wheel, derives from Wheel, exposes Interface Turn One is for categorizing behavior that can be offered across a diverse range of things, the other is for modelling an ontology of things.
In short the differences are the following: Syntactical Differences Between Interface and Abstract Class: Methods and members of an abstract class can have any visibility. All methods of an interface must be public. //Does not hold true from Java 9 anymore A concrete child class of an Abstract Class must define all the abstract methods. An Abstract child class can have abstract methods. An interface extending another interface need not provide default implementation for methods inherited from the parent interface. A child class can only extend a single class. An interface can extend multiple interfaces. A class can implement multiple interfaces. A child class can define abstract methods with the same or less restrictive visibility, whereas class implementing an interface must define all interface methods as public. Abstract Classes can have constructors but not interfaces. Interfaces from Java 9 have private static methods. In Interfaces now: public static - supported public abstract - supported public default - supported private static - supported private abstract - compile error private default - compile error private - supported
Many junior developers make the mistake of thinking of interfaces, abstract and concrete classes as slight variations of the same thing, and choose one of them purely on technical grounds: Do I need multiple inheritance? Do I need some place to put common methods? Do I need to bother with something other than just a concrete class? This is wrong, and hidden in these questions is the main problem: "I". When you write code for yourself, by yourself, you rarely think of other present or future developers working on or with your code. Interfaces and abstract classes, although apparently similar from a technical point of view, have completely different meanings and purposes. Summary An interface defines a contract that some implementation will fulfill for you. An abstract class provides a default behavior that your implementation can reuse. Alternative summary An interface is for defining public APIs An abstract class is for internal use, and for defining SPIs On the importance of hiding implementation details A concrete class does the actual work, in a very specific way. For example, an ArrayList uses a contiguous area of memory to store a list of objects in a compact manner which offers fast random access, iteration, and in-place changes, but is terrible at insertions, deletions, and occasionally even additions; meanwhile, a LinkedList uses double-linked nodes to store a list of objects, which instead offers fast iteration, in-place changes, and insertion/deletion/addition, but is terrible at random access. These two types of lists are optimized for different use cases, and it matters a lot how you're going to use them. When you're trying to squeeze performance out of a list that you're heavily interacting with, and when picking the type of list is up to you, you should carefully pick which one you're instantiating. On the other hand, high level users of a list don't really care how it is actually implemented, and they should be insulated from these details. Let's imagine that Java didn't expose the List interface, but only had a concrete List class that's actually what LinkedList is right now. All Java developers would have tailored their code to fit the implementation details: avoid random access, add a cache to speed up access, or just reimplement ArrayList on their own, although it would be incompatible with all the other code that actually works with List only. That would be terrible... But now imagine that the Java masters actually realize that a linked list is terrible for most actual use cases, and decided to switch over to an array list for their only List class available. This would affect the performance of every Java program in the world, and people wouldn't be happy about it. And the main culprit is that implementation details were available, and the developers assumed that those details are a permanent contract that they can rely on. This is why it's important to hide implementation details, and only define an abstract contract. This is the purpose of an interface: define what kind of input a method accepts, and what kind of output is expected, without exposing all the guts that would tempt programmers to tweak their code to fit the internal details that might change with any future update. An abstract class is in the middle between interfaces and concrete classes. It is supposed to help implementations share common or boring code. For example, AbstractCollection provides basic implementations for isEmpty based on size is 0, contains as iterate and compare, addAll as repeated add, and so on. This lets implementations focus on the crucial parts that differentiate between them: how to actually store and retrieve data. APIs versus SPIs Interfaces are low-cohesion gateways between different parts of code. They allow libraries to exist and evolve without breaking every library user when something changes internally. It's called Application Programming Interface, not Application Programming Classes. On a smaller scale, they also allow multiple developers to collaborate successfully on large scale projects, by separating different modules through well documented interfaces. Abstract classes are high-cohesion helpers to be used when implementing an interface, assuming some level of implementation details. Alternatively, abstract classes are used for defining SPIs, Service Provider Interfaces. The difference between an API and an SPI is subtle, but important: for an API, the focus is on who uses it, and for an SPI the focus is on who implements it. Adding methods to an API is easy, all existing users of the API will still compile. Adding methods to an SPI is hard, since every service provider (concrete implementation) will have to implement the new methods. If interfaces are used to define an SPI, a provider will have to release a new version whenever the SPI contract changes. If abstract classes are used instead, new methods could either be defined in terms of existing abstract methods, or as empty throw not implemented exception stubs, which will at least allow an older version of a service implementation to still compile and run. A note on Java 8 and default methods Although Java 8 introduced default methods for interfaces, which makes the line between interfaces and abstract classes even blurrier, this wasn't so that implementations can reuse code, but to make it easier to change interfaces that serve both as an API and as an SPI (or are wrongly used for defining SPIs instead of abstract classes). Which one to use? Is the thing supposed to be publicly used by other parts of the code, or by other external code? Add an interface to it to hide the implementation details from the public abstract contract, which is the general behavior of the thing. Is the thing something that's supposed to have multiple implementations with a lot of code in common? Make both an interface and an abstract, incomplete implementation. Is there ever going to be only one implementation, and nobody else will use it? Just make it a concrete class. "ever" is long time, you could play it safe and still add an interface on top of it. A corollary: the other way around is often wrongly done: when using a thing, always try to use the most generic class/interface that you actually need. In other words, don't declare your variables as ArrayList theList = new ArrayList(), unless you actually have a very strong dependency on it being an array list, and no other type of list would cut it for you. Use List theList = new ArrayList instead, or even Collection theCollection = new ArrayList if the fact that it's a list, and not any other type of collection doesn't actually matter.
Not really the answer to the original question, but once you have the answer to the difference between them, you will enter the when-to-use-each dilemma: When to use interfaces or abstract classes? When to use both? I've limited knowledge of OOP, but seeing interfaces as an equivalent of an adjective in grammar has worked for me until now (correct me if this method is bogus!). For example, interface names are like attributes or capabilities you can give to a class, and a class can have many of them: ISerializable, ICountable, IList, ICacheable, IHappy, ...
You can find clear difference between interface and abstract class. Interface Interface only contains abstract methods. Force users to implement all methods when implements the interface. Contains only final and static variables. Declare using interface keyword. All methods of an interface must be defined as public. An interface can extend or a class can implement multiple other interfaces. Abstract class Abstract class contains abstract and non-abstract methods. Does not force users to implement all methods when inherited the abstract class. Contains all kinds of variables including primitive and non-primitive Declare using abstract keyword. Methods and members of an abstract class can be defined with any visibility. A child class can only extend a single class (abstract or concrete).
I am 10 yrs late to the party but would like to attempt any way. Wrote a post about the same on medium few days back. Thought of posting it here. tl;dr; When you see “Is A” relationship use inheritance/abstract class. when you see “has a” relationship create member variables. When you see “relies on external provider” implement (not inherit) an interface. Interview Question: What is the difference between an interface and an abstract class? And how do you decide when to use what? I mostly get one or all of the below answers: Answer 1: You cannot create an object of abstract class and interfaces. ZK (That’s my initials): You cannot create an object of either. So this is not a difference. This is a similarity between an interface and an abstract class. Counter Question: Why can’t you create an object of abstract class or interface? Answer 2: Abstract classes can have a function body as partial/default implementation. ZK: Counter Question: So if I change it to a pure abstract class, marking all the virtual functions as abstract and provide no default implementation for any virtual function. Would that make abstract classes and interfaces the same? And could they be used interchangeably after that? Answer 3: Interfaces allow multi-inheritance and abstract classes don’t. ZK: Counter Question: Do you really inherit from an interface? or do you just implement an interface and, inherit from an abstract class? What’s the difference between implementing and inheriting? These counter questions throw candidates off and make most scratch their heads or just pass to the next question. That makes me think people need help with these basic building blocks of Object-Oriented Programming. The answer to the original question and all the counter questions is found in the English language and the UML. You must know at least below to understand these two constructs better. Common Noun: A common noun is a name given “in common” to things of the same class or kind. For e.g. fruits, animals, city, car etc. Proper Noun: A proper noun is the name of an object, place or thing. Apple, Cat, New York, Honda Accord etc. Car is a Common Noun. And Honda Accord is a Proper Noun, and probably a Composit Proper noun, a proper noun made using two nouns. Coming to the UML Part. You should be familiar with below relationships: Is A Has A Uses Let’s consider the below two sentences. - HondaAccord Is A Car? - HondaAccord Has A Car? Which one sounds correct? Plain English and comprehension. HondaAccord and Cars share an “Is A” relationship. Honda accord doesn’t have a car in it. It “is a” car. Honda Accord “has a” music player in it. When two entities share the “Is A” relationship it’s a better candidate for inheritance. And Has a relationship is a better candidate for creating member variables. With this established our code looks like this: abstract class Car { string color; int speed; } class HondaAccord : Car { MusicPlayer musicPlayer; } Now Honda doesn't manufacture music players. Or at least it’s not their main business. So they reach out to other companies and sign a contract. If you receive power here and the output signal on these two wires it’ll play just fine on these speakers. This makes Music Player a perfect candidate for an interface. You don’t care who provides support for it as long as the connections work just fine. You can replace the MusicPlayer of LG with Sony or the other way. And it won’t change a thing in Honda Accord. Why can’t you create an object of abstract classes? Because you can’t walk into a showroom and say give me a car. You’ll have to provide a proper noun. What car? Probably a honda accord. And that’s when a sales agent could get you something. Why can’t you create an object of an interface? Because you can’t walk into a showroom and say give me a contract of music player. It won’t help. Interfaces sit between consumers and providers just to facilitate an agreement. What will you do with a copy of the agreement? It won’t play music. Why do interfaces allow multiple inheritance? Interfaces are not inherited. Interfaces are implemented. The interface is a candidate for interaction with the external world. Honda Accord has an interface for refueling. It has interfaces for inflating tires. And the same hose that is used to inflate a football. So the new code will look like below: abstract class Car { string color; int speed; } class HondaAccord : Car, IInflateAir, IRefueling { MusicPlayer musicPlayer; } And the English will read like this “Honda Accord is a Car that supports inflating tire and refueling”.
Key Points: Abstract class can have property, Data fields ,Methods (complete / incomplete) both. If method or Properties define in abstract keyword that must override in derived class.(its work as a tightly coupled functionality) If define abstract keyword for method or properties in abstract class you can not define body of method and get/set value for properties and that must override in derived class. Abstract class does not support multiple inheritance. Abstract class contains Constructors. An abstract class can contain access modifiers for the subs, functions, properties. Only Complete Member of abstract class can be Static. An interface can inherit from another interface only and cannot inherit from an abstract class, where as an abstract class can inherit from another abstract class or another interface. Advantage: It is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards. If various implementations are of the same kind and use common behavior or status then abstract class is better to use. If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly. Its allow fast execution than interface.(interface Requires more time to find the actual method in the corresponding classes.) It can use for tight and loosely coupling. find details here... http://pradeepatkari.wordpress.com/2014/11/20/interface-and-abstract-class-in-c-oops/
The shortest way to sum it up is that an interface is: Fully abstract, apart from default and static methods; while it has definitions (method signatures + implementations) for default and static methods, it only has declarations (method signatures) for other methods. Subject to laxer rules than classes (a class can implement multiple interfaces, and an interface can inherit from multiple interfaces). All variables are implicitly constant, whether specified as public static final or not. All members are implicitly public, whether specified as such or not. Generally used as a guarantee that the implementing class will have the specified features and/or be compatible with any other class which implements the same interface. Meanwhile, an abstract class is: Anywhere from fully abstract to fully implemented, with a tendency to have one or more abstract methods. Can contain both declarations and definitions, with declarations marked as abstract. A full-fledged class, and subject to the rules that govern other classes (can only inherit from one class), on the condition that it cannot be instantiated (because there's no guarantee that it's fully implemented). Can have non-constant member variables. Can implement member access control, restricting members as protected, private, or private package (unspecified). Generally used either to provide as much of the implementation as can be shared by multiple subclasses, or to provide as much of the implementation as the programmer is able to supply. Or, if we want to boil it all down to a single sentence: An interface is what the implementing class has, but an abstract class is what the subclass is.
Inheritance is used for two purposes: To allow an object to regard parent-type data members and method implementations as its own. To allow a reference to an objects of one type to be used by code which expects a reference to supertype object. In languages/frameworks which support generalized multiple inheritance, there is often little need to classify a type as either being an "interface" or an "abstract class". Popular languages and frameworks, however, will allow a type to regard one other type's data members or method implementations as its own even though they allow a type to be substitutable for an arbitrary number of other types. Abstract classes may have data members and method implementations, but can only be inherited by classes which don't inherit from any other classes. Interfaces put almost no restrictions on the types which implement them, but cannot include any data members or method implementations. There are times when it's useful for types to be substitutable for many different things; there are other times when it's useful for objects to regard parent-type data members and method implementations as their own. Making a distinction between interfaces and abstract classes allows each of those abilities to be used in cases where it is most relevant.
Differences between abstract class and interface on behalf of real implementation. Interface: It is a keyword and it is used to define the template or blue print of an object and it forces all the sub classes would follow the same prototype,as for as implementation, all the sub classes are free to implement the functionality as per it's requirement. Some of other use cases where we should use interface. Communication between two external objects(Third party integration in our application) done through Interface here Interface works as Contract. Abstract Class: Abstract,it is a keyword and when we use this keyword before any class then it becomes abstract class.It is mainly used when we need to define the template as well as some default functionality of an object that is followed by all the sub classes and this way it removes the redundant code and one more use cases where we can use abstract class, such as we want no other classes can directly instantiate an object of the class, only derived classes can use the functionality. Example of Abstract Class: public abstract class DesireCar { //It is an abstract method that defines the prototype. public abstract void Color(); // It is a default implementation of a Wheel method as all the desire cars have the same no. of wheels. // and hence no need to define this in all the sub classes in this way it saves the code duplicasy public void Wheel() { Console.WriteLine("Car has four wheel"); } } **Here is the sub classes:** public class DesireCar1 : DesireCar { public override void Color() { Console.WriteLine("This is a red color Desire car"); } } public class DesireCar2 : DesireCar { public override void Color() { Console.WriteLine("This is a red white Desire car"); } } Example Of Interface: public interface IShape { // Defines the prototype(template) void Draw(); } // All the sub classes follow the same template but implementation can be different. public class Circle : IShape { public void Draw() { Console.WriteLine("This is a Circle"); } } public class Rectangle : IShape { public void Draw() { Console.WriteLine("This is a Rectangle"); } }
I'd like to add one more difference which makes sense. For example, you have a framework with thousands of lines of code. Now if you want to add a new feature throughout the code using a method enhanceUI(), then it's better to add that method in abstract class rather in interface. Because, if you add this method in an interface then you should implement it in all the implemented class but it's not the case if you add the method in abstract class.
To give a simple but clear answer, it helps to set the context : you use both when you do not want to provide full implementations. The main difference then is an interface has no implementation at all (only methods without a body) while abstract classes can have members and methods with a body as well, i.e. can be partially implemented.
usually Abstract class used for core of something but interface used for appending peripheral. when you want to create base type for vehicle you should use abstract class but if you want to add some functionality or property that is not part of base concept of vehicle you should use interface,for example you want to add "ToJSON()" function. interface has wide range of abstraction rather than abstract class. you can see this in passing arguments.look this example: if you use vehicle as argument you just can use one of its derived type (bus or car-same category-just vehicle category). but when you use IMoveable interface as argument you have more choices.
The topic of abstract classes vs interfaces is mostly about semantics. Abstract classes act in different programming languages often as a superset of interfaces, except one thing and that is, that you can implement multiple interfaces, but inherit only one class. An interface defines what something must be able to do; like a contract, but does not provide an implementation of it. An abstract class defines what something is and it commonly hosts shared code between the subclasses. For example a Formatter should be able to format() something. The common semantics to describe something like that would be to create an interface IFormatter with a declaration of format() that acts like a contract. But IFormatter does not describe what something is, but just what it should be able to to. The common semantics to describe what something actually is, is to create a class. In this case we create an abstract class... So we create an abstract class Formatter which implements the interface. That is a very descriptive code, because we now know we have a Formatter and we now know what every Formatter must be able to do. Also one very important topic is documentation (at least for some people...). In your documentation you probably want to explain within your subclasses what a Formatter actually is. It is very convenient to have an abstract class Formatter to which documentation you can link to within your subclasses. That is very convenient and generic. On the other hand if you do not have an abstract class Formatter and only an interface IFormatter you would have to explain in each of your subclasses what a Formatter actucally is, because an interface is a contract and you would not describe what a Formatter actually is within the documentation of an interface — at least it would be not something common to do and you would break the semantics that most developers consider to be correct. Note: It is a very common pattern to make an abstract class implement an interface.
An abstract class is a class whose object cannot be created or a class which cannot be instantiated. An abstract method makes a class abstract. An abstract class needs to be inherited in order to override the methods that are declared in the abstract class. No restriction on access specifiers. An abstract class can have constructor and other concrete(non abstarct methods ) methods in them but interface cannot have. An interface is a blueprint/template of methods.(eg. A house on a paper is given(interface house) and different architects will use their ideas to build it(the classes of architects implementing the house interface) . It is a collection of abstract methods , default methods , static methods , final variables and nested classes. All members will be either final or public , protected and private access specifiers are not allowed.No object creation is allowed. A class has to be made in order to use the implementing interface and also to override the abstract method declared in the interface. An interface is a good example of loose coupling(dynamic polymorphism/dynamic binding) An interface implements polymorphism and abstraction.It tells what to do but how to do is defined by the implementing class. For Eg. There's a car company and it wants that some features to be same for all the car it is manufacturing so for that the company would be making an interface vehicle which will have those features and different classes of car(like Maruti Suzkhi , Maruti 800) will override those features(functions). Why interface when we already have abstract class? Java supports only multilevel and hierarchal inheritance but with the help of interface we can implement multiple inheritance.
In an interface all methods must be only definitions, not single one should be implemented. But in an abstract class there must an abstract method with only definition, but other methods can be also in the abstract class with implementation...
A use for multiple inheritance?
Can anyone think of any situation to use multiple inheritance? Every case I can think of can be solved by the method operator AnotherClass() { return this->something.anotherClass; }
Most uses of full scale Multiple inheritance are for mixins. As an example: class DraggableWindow : Window, Draggable { } class SkinnableWindow : Window, Skinnable { } class DraggableSkinnableWindow : Window, Draggable, Skinnable { } etc... In most cases, it's best to use multiple inheritance to do strictly interface inheritance. class DraggableWindow : Window, IDraggable { } Then you implement the IDraggable interface in your DraggableWindow class. It's WAY too hard to write good mixin classes. The benefit of the MI approach (even if you are only using Interface MI) is that you can then treat all kinds of different Windows as Window objects, but have the flexibility to create things that would not be possible (or more difficult) with single inheritance. For example, in many class frameworks you see something like this: class Control { } class Window : Control { } class Textbox : Control { } Now, suppose you wanted a Textbox with Window characteristics? Like being dragable, having a titlebar, etc... You could do something like this: class WindowedTextbox : Control, IWindow, ITexbox { } In the single inheritance model, you can't easily inherit from both Window and Textbox without having some problems with duplicate Control objects and other kinds of problems. You can also treat a WindowedTextbox as a Window, a Textbox, or a Control. Also, to address your .anotherClass() idiom, .anotherClass() returns a different object, while multiple inheritance allows the same object to be used for different purposes.
I find multiple inheritance particularly useful when using mixin classes. As stated in Wikipedia: In object-oriented programming languages, a mixin is a class that provides a certain functionality to be inherited by a subclass, but is not meant to stand alone. An example of how our product uses mixin classes is for configuration save and restore purposes. There is an abstract mixin class which defines a set of pure virtual methods. Any class which is saveable inherits from the save/restore mixin class which automatically gives them the appropriate save/restore functionality. But they may also inherit from other classes as part of their normal class structure, so it is quite common for these classes to use multiple inheritance in this respect. An example of multiple inheritance: class Animal { virtual void KeepCool() const = 0; } class Vertebrate { virtual void BendSpine() { }; } class Dog : public Animal, public Vertebrate { void KeepCool() { Pant(); } } What is most important when doing any form of public inheritance (single or multiple) is to respect the is a relationship. A class should only inherit from one or more classes if it "is" one of those objects. If it simply "contains" one of those objects, aggregation or composition should be used instead. The example above is well structured because a dog is an animal, and also a vertebrate.
Most people use multiple-inheritance in the context of applying multiple interfaces to a class. This is the approach Java and C#, among others, enforce. C++ allows you to apply multiple base classes fairly freely, in an is-a relationship between types. So, you can treat a derived object like any of its base classes. Another use, as LeopardSkinPillBoxHat points out, is in mix-ins. An excellent example of this is the Loki library, from Andrei Alexandrescu's book Modern C++ Design. He uses what he terms policy classes that specify the behavior or the requirements of a given class through inheritance. Yet another use is one that simplifies a modular approach that allows API-independence through the use of sister-class delegation in the oft-dreaded diamond hierarchy. The uses for MI are many. The potential for abuse is even greater.
Java has interfaces. C++ has not. Therefore, multiple inheritance can be used to emulate the interface feature. If you're a C# and Java programmer, every time you use a class that extends a base class but also implements a few interfaces, you are sort of admitting multiple inheritance can be useful in some situations.
I think it would be most useful for boilerplate code. For example, the IDisposable pattern is exactly the same for all classes in .NET. So why re-type that code over and over again? Another example is ICollection. The vast majority of the interface methods are implemented exactly the same. There are only a couple of methods that are actually unique to your class. Unfortunately multiple-inheritance is very easy to abuse. People will quickly start doing silly things like LabelPrinter class inherit from their TcpIpConnector class instead of merely contain it.
One case I worked on recently involved network enabled label printers. We need to print labels, so we have a class LabelPrinter. This class has virtual calls for printing several different labels. I also have a generic class for TCP/IP connected things, which can connect, send and receive. So, when I needed to implement a printer, it inherited from both the LabelPrinter class and the TcpIpConnector class.
I think fmsf example is a bad idea. A car is not a tire or an engine. You should be using composition for that. MI (of implementation or interface) can be used to add functionality. These are often called mixin classes.. Imagine you have a GUI. There is view class that handles drawing and a Drag&Drop class that handles dragging. If you have an object that does both you would have a class like class DropTarget{ public void Drop(DropItem & itemBeingDropped); ... } class View{ public void Draw(); ... } /* View you can drop items on */ class DropView:View,DropTarget{ }
It is true that composition of an interface (Java or C# like) plus forwarding to a helper can emulate many of the common uses of multiple inheritance (notably mixins). However this is done at the cost of that forwarding code being repeated (and violating DRY). MI does open a number of difficult areas, and more recently some language designers have taken decisions that the potential pitfalls of MI outweigh the benefits. Similarly one can argue against generics (heterogeneous containers do work, loops can be replaced with (tail) recursion) and almost any other feature of programming languages. Just because it is possible to work without a feature does not mean that that feature is valueless or cannot help to effectively express solutions. A rich diversity of languages, and language families makes it easier for us as developers to pick good tools that solve the business problem at hand. My toolbox contains many items I rarely use, but on those occasions I do not want to treat everything as a nail.
An example of how our product uses mixin classes is for configuration save and restore purposes. There is an abstract mixin class which defines a set of pure virtual methods. Any class which is saveable inherits from the save/restore mixin class which automatically gives them the appropriate save/restore functionality. This example doesn't really illustrate the usefulness of multiple inheritance. What being defined here is an INTERFACE. Multiple inheritance allows you to inherit behavior as well. Which is the point of mixins. An example; because of a need to preserve backwards compatibility I have to implement my own serialization methods. So every object gets a Read and Store method like this. Public Sub Store(ByVal File As IBinaryWriter) Public Sub Read(ByVal File As IBinaryReader) I also want to be able to assign and clone object as well. So I would like this on every object. Public Sub Assign(ByVal tObject As <Class_Name>) Public Function Clone() As <Class_Name> Now in VB6 I have this code repeated over and over again. Public Assign(ByVal tObject As ObjectClass) Me.State = tObject.State End Sub Public Function Clone() As ObjectClass Dim O As ObjectClass Set O = New ObjectClass O.State = Me.State Set Clone = 0 End Function Public Property Get State() As Variant StateManager.Clear Me.Store StateManager State = StateManager.Data End Property Public Property Let State(ByVal RHS As Variant) StateManager.Data = RHS Me.Read StateManager End Property Note that Statemanager is a stream that read and stores byte arrays. This code is repeated dozens of times. Now in .NET i am able to get around this by using a combination of generics and inheritance. My object under the .NET version get Assign, Clone, and State when they inherit from MyAppBaseObject. But I don't like the fact that every object inherits from MyAppBaseObject. I rather just mix in the the Assign Clone interface AND BEHAVIOR. Better yet mix in separately the Read and Store interface then being able to mix in Assign and Clone. It would be cleaner code in my opinion. But the times where I reuse behavior are DWARFED by the time I use Interface. This is because the goal of most object hierarchies are NOT about reusing behavior but precisely defining the relationship between different objects. Which interfaces are designed for. So while it would be nice that C# (or VB.NET) had some ability to do this it isn't a show stopper in my opinion. The whole reason that this is even an issue that that C++ fumbled the ball at first when it came to the interface vs inheritance issue. When OOP debuted everybody thought that behavior reuse was the priority. But this proved to be a chimera and only useful for specific circumstances, like making a UI framework. Later the idea of mixins (and other related concepts in aspect oriented programming) were developed. Multiple inheritance was found useful in creating mix-ins. But C# was developed just before this was widely recognized. Likely an alternative syntax will be developed to do this.
I suspect that in C++, MI is best use as part of a framework (the mix-in classes previously discussed). The only thing I know for sure is that every time I've tried to use it in my apps, I've ended up regretting the choice, and often tearing it out and replacing it with generated code. MI is one more of those 'use it if you REALLY need it, but make sure you REALLY need it' tools.
The following example is mostly something I see often in C++: sometimes it may be necessary due to utility classes that you need but because of their design cannot be used through composition (at least not efficiently or without making the code even messier than falling back on mult. inheritance). A good example is you have an abstract base class A and a derived class B, and B also needs to be a kind of serializable class, so it has to derive from, let's say, another abstract class called Serializable. It's possible to avoid MI, but if Serializable only contains a few virtual methods and needs deep access to the private members of B, then it may be worth muddying the inheritance tree just to avoid making friend declarations and giving away access to B's internals to some helper composition class.
I had to use it today, actually... Here was my situation - I had a domain model represented in memory where an A contained zero or more Bs(represented in an array), each B has zero or more Cs, and Cs to Ds. I couldn't change the fact that they were arrays (the source for these arrays were from automatically generated code from the build process). Each instance needed to keep track of which index in the parent array they belonged in. They also needed to keep track of the instance of their parent (too much detail as to why). I wrote something like this (there was more to it, and this is not syntactically correct, it's just an example): class Parent { add(Child c) { children.add(c); c.index = children.Count-1; c.parent = this; } Collection<Child> children } class Child { Parent p; int index; } Then, for the domain types, I did this: class A : Parent class B : Parent, Child class C : Parent, Child class D : Child The actually implementation was in C# with interfaces and generics, and I couldn't do the multiple inheritance like I would have if the language supported it (some copy paste had to be done). So, I thought I'd search SO to see what people think of multiple inheritance, and I got your question ;) I couldn't use your solution of the .anotherClass, because of the implementation of add for Parent (references this - and I wanted this to not be some other class). It got worse because the generated code had A subclass something else that was neither a parent or a child...more copy paste.