Interface Segregation Principle and Convenience/Helper Methods - oop

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);
}

Related

[SELENIUM]Webdriver driver = new FirefoxDriver() cn anyone say how the constructor name is different from class name here [duplicate]

I have seen this mentioned a few times and I am not clear on what it means. When and why would you do this?
I know what interfaces do, but the fact I am not clear on this makes me think I am missing out on using them correctly.
Is it just so if you were to do:
IInterface classRef = new ObjectWhatever()
You could use any class that implements IInterface? When would you need to do that? The only thing I can think of is if you have a method and you are unsure of what object will be passed except for it implementing IInterface. I cannot think how often you would need to do that.
Also, how could you write a method that takes in an object that implements an interface? Is that possible?
There are some wonderful answers on here to this questions that get into all sorts of great detail about interfaces and loosely coupling code, inversion of control and so on. There are some fairly heady discussions, so I'd like to take the opportunity to break things down a bit for understanding why an interface is useful.
When I first started getting exposed to interfaces, I too was confused about their relevance. I didn't understand why you needed them. If we're using a language like Java or C#, we already have inheritance and I viewed interfaces as a weaker form of inheritance and thought, "why bother?" In a sense I was right, you can think of interfaces as sort of a weak form of inheritance, but beyond that I finally understood their use as a language construct by thinking of them as a means of classifying common traits or behaviors that were exhibited by potentially many non-related classes of objects.
For example -- say you have a SIM game and have the following classes:
class HouseFly inherits Insect {
void FlyAroundYourHead(){}
void LandOnThings(){}
}
class Telemarketer inherits Person {
void CallDuringDinner(){}
void ContinueTalkingWhenYouSayNo(){}
}
Clearly, these two objects have nothing in common in terms of direct inheritance. But, you could say they are both annoying.
Let's say our game needs to have some sort of random thing that annoys the game player when they eat dinner. This could be a HouseFly or a Telemarketer or both -- but how do you allow for both with a single function? And how do you ask each different type of object to "do their annoying thing" in the same way?
The key to realize is that both a Telemarketer and HouseFly share a common loosely interpreted behavior even though they are nothing alike in terms of modeling them. So, let's make an interface that both can implement:
interface IPest {
void BeAnnoying();
}
class HouseFly inherits Insect implements IPest {
void FlyAroundYourHead(){}
void LandOnThings(){}
void BeAnnoying() {
FlyAroundYourHead();
LandOnThings();
}
}
class Telemarketer inherits Person implements IPest {
void CallDuringDinner(){}
void ContinueTalkingWhenYouSayNo(){}
void BeAnnoying() {
CallDuringDinner();
ContinueTalkingWhenYouSayNo();
}
}
We now have two classes that can each be annoying in their own way. And they do not need to derive from the same base class and share common inherent characteristics -- they simply need to satisfy the contract of IPest -- that contract is simple. You just have to BeAnnoying. In this regard, we can model the following:
class DiningRoom {
DiningRoom(Person[] diningPeople, IPest[] pests) { ... }
void ServeDinner() {
when diningPeople are eating,
foreach pest in pests
pest.BeAnnoying();
}
}
Here we have a dining room that accepts a number of diners and a number of pests -- note the use of the interface. This means that in our little world, a member of the pests array could actually be a Telemarketer object or a HouseFly object.
The ServeDinner method is called when dinner is served and our people in the dining room are supposed to eat. In our little game, that's when our pests do their work -- each pest is instructed to be annoying by way of the IPest interface. In this way, we can easily have both Telemarketers and HouseFlys be annoying in each of their own ways -- we care only that we have something in the DiningRoom object that is a pest, we don't really care what it is and they could have nothing in common with other.
This very contrived pseudo-code example (that dragged on a lot longer than I anticipated) is simply meant to illustrate the kind of thing that finally turned the light on for me in terms of when we might use an interface. I apologize in advance for the silliness of the example, but hope that it helps in your understanding. And, to be sure, the other posted answers you've received here really cover the gamut of the use of interfaces today in design patterns and development methodologies.
The specific example I used to give to students is that they should write
List myList = new ArrayList(); // programming to the List interface
instead of
ArrayList myList = new ArrayList(); // this is bad
These look exactly the same in a short program, but if you go on to use myList 100 times in your program you can start to see a difference. The first declaration ensures that you only call methods on myList that are defined by the List interface (so no ArrayList specific methods). If you've programmed to the interface this way, later on you can decide that you really need
List myList = new TreeList();
and you only have to change your code in that one spot. You already know that the rest of your code doesn't do anything that will be broken by changing the implementation because you programmed to the interface.
The benefits are even more obvious (I think) when you're talking about method parameters and return values. Take this for example:
public ArrayList doSomething(HashMap map);
That method declaration ties you to two concrete implementations (ArrayList and HashMap). As soon as that method is called from other code, any changes to those types probably mean you're going to have to change the calling code as well. It would be better to program to the interfaces.
public List doSomething(Map map);
Now it doesn't matter what kind of List you return, or what kind of Map is passed in as a parameter. Changes that you make inside the doSomething method won't force you to change the calling code.
Programming to an interface is saying, "I need this functionality and I don't care where it comes from."
Consider (in Java), the List interface versus the ArrayList and LinkedList concrete classes. If all I care about is that I have a data structure containing multiple data items that I should access via iteration, I'd pick a List (and that's 99% of the time). If I know that I need constant-time insert/delete from either end of the list, I might pick the LinkedList concrete implementation (or more likely, use the Queue interface). If I know I need random access by index, I'd pick the ArrayList concrete class.
Programming to an interface has absolutely nothing to do with abstract interfaces like we see in Java or .NET. It isn't even an OOP concept.
What it means is don't go messing around with the internals of an object or data structure. Use the Abstract Program Interface, or API, to interact with your data. In Java or C# that means using public properties and methods instead of raw field access. For C that means using functions instead of raw pointers.
EDIT: And with databases it means using views and stored procedures instead of direct table access.
Using interfaces is a key factor in making your code easily testable in addition to removing unnecessary couplings between your classes. By creating an interface that defines the operations on your class, you allow classes that want to use that functionality the ability to use it without depending on your implementing class directly. If later on you decide to change and use a different implementation, you need only change the part of the code where the implementation is instantiated. The rest of the code need not change because it depends on the interface, not the implementing class.
This is very useful in creating unit tests. In the class under test you have it depend on the interface and inject an instance of the interface into the class (or a factory that allows it to build instances of the interface as needed) via the constructor or a property settor. The class uses the provided (or created) interface in its methods. When you go to write your tests, you can mock or fake the interface and provide an interface that responds with data configured in your unit test. You can do this because your class under test deals only with the interface, not your concrete implementation. Any class implementing the interface, including your mock or fake class, will do.
EDIT: Below is a link to an article where Erich Gamma discusses his quote, "Program to an interface, not an implementation."
http://www.artima.com/lejava/articles/designprinciples.html
You should look into Inversion of Control:
Martin Fowler: Inversion of Control Containers and the Dependency Injection pattern
Wikipedia: Inversion of Control
In such a scenario, you wouldn't write this:
IInterface classRef = new ObjectWhatever();
You would write something like this:
IInterface classRef = container.Resolve<IInterface>();
This would go into a rule-based setup in the container object, and construct the actual object for you, which could be ObjectWhatever. The important thing is that you could replace this rule with something that used another type of object altogether, and your code would still work.
If we leave IoC off the table, you can write code that knows that it can talk to an object that does something specific, but not which type of object or how it does it.
This would come in handy when passing parameters.
As for your parenthesized question "Also, how could you write a method that takes in an object that implements an Interface? Is that possible?", in C# you would simply use the interface type for the parameter type, like this:
public void DoSomethingToAnObject(IInterface whatever) { ... }
This plugs right into the "talk to an object that does something specific." The method defined above knows what to expect from the object, that it implements everything in IInterface, but it doesn't care which type of object it is, only that it adheres to the contract, which is what an interface is.
For instance, you're probably familiar with calculators and have probably used quite a few in your days, but most of the time they're all different. You, on the other hand, knows how a standard calculator should work, so you're able to use them all, even if you can't use the specific features that each calculator has that none of the other has.
This is the beauty of interfaces. You can write a piece of code, that knows that it will get objects passed to it that it can expect certain behavior from. It doesn't care one hoot what kind of object it is, only that it supports the behavior needed.
Let me give you a concrete example.
We have a custom-built translation system for windows forms. This system loops through controls on a form and translate text in each. The system knows how to handle basic controls, like the-type-of-control-that-has-a-Text-property, and similar basic stuff, but for anything basic, it falls short.
Now, since controls inherit from pre-defined classes that we have no control over, we could do one of three things:
Build support for our translation system to detect specifically which type of control it is working with, and translate the correct bits (maintenance nightmare)
Build support into base classes (impossible, since all the controls inherit from different pre-defined classes)
Add interface support
So we did nr. 3. All our controls implement ILocalizable, which is an interface that gives us one method, the ability to translate "itself" into a container of translation text/rules. As such, the form doesn't need to know which kind of control it has found, only that it implements the specific interface, and knows that there is a method where it can call to localize the control.
Code to the Interface Not the Implementation has NOTHING to do with Java, nor its Interface construct.
This concept was brought to prominence in the Patterns / Gang of Four books but was most probably around well before that. The concept certainly existed well before Java ever existed.
The Java Interface construct was created to aid in this idea (among other things), and people have become too focused on the construct as the centre of the meaning rather than the original intent. However, it is the reason we have public and private methods and attributes in Java, C++, C#, etc.
It means just interact with an object or system's public interface. Don't worry or even anticipate how it does what it does internally. Don't worry about how it is implemented. In object-oriented code, it is why we have public vs. private methods/attributes. We are intended to use the public methods because the private methods are there only for use internally, within the class. They make up the implementation of the class and can be changed as required without changing the public interface. Assume that regarding functionality, a method on a class will perform the same operation with the same expected result every time you call it with the same parameters. It allows the author to change how the class works, its implementation, without breaking how people interact with it.
And you can program to the interface, not the implementation without ever using an Interface construct. You can program to the interface not the implementation in C++, which does not have an Interface construct. You can integrate two massive enterprise systems much more robustly as long as they interact through public interfaces (contracts) rather than calling methods on objects internal to the systems. The interfaces are expected to always react the same expected way given the same input parameters; if implemented to the interface and not the implementation. The concept works in many places.
Shake the thought that Java Interfaces have anything what-so-ever to do with the concept of 'Program to the Interface, Not the Implementation'. They can help apply the concept, but they are not the concept.
It sounds like you understand how interfaces work but are unsure of when to use them and what advantages they offer. Here are a few examples of when an interface would make sense:
// if I want to add search capabilities to my application and support multiple search
// engines such as Google, Yahoo, Live, etc.
interface ISearchProvider
{
string Search(string keywords);
}
then I could create GoogleSearchProvider, YahooSearchProvider, LiveSearchProvider, etc.
// if I want to support multiple downloads using different protocols
// HTTP, HTTPS, FTP, FTPS, etc.
interface IUrlDownload
{
void Download(string url)
}
// how about an image loader for different kinds of images JPG, GIF, PNG, etc.
interface IImageLoader
{
Bitmap LoadImage(string filename)
}
then create JpegImageLoader, GifImageLoader, PngImageLoader, etc.
Most add-ins and plugin systems work off interfaces.
Another popular use is for the Repository pattern. Say I want to load a list of zip codes from different sources
interface IZipCodeRepository
{
IList<ZipCode> GetZipCodes(string state);
}
then I could create an XMLZipCodeRepository, SQLZipCodeRepository, CSVZipCodeRepository, etc. For my web applications, I often create XML repositories early on so I can get something up and running before the SQL Database is ready. Once the database is ready I write an SQLRepository to replace the XML version. The rest of my code remains unchanged since it runs solely off of interfaces.
Methods can accept interfaces such as:
PrintZipCodes(IZipCodeRepository zipCodeRepository, string state)
{
foreach (ZipCode zipCode in zipCodeRepository.GetZipCodes(state))
{
Console.WriteLine(zipCode.ToString());
}
}
It makes your code a lot more extensible and easier to maintain when you have sets of similar classes. I am a junior programmer, so I am no expert, but I just finished a project that required something similar.
I work on client side software that talks to a server running a medical device. We are developing a new version of this device that has some new components that the customer must configure at times. There are two types of new components, and they are different, but they are also very similar. Basically, I had to create two config forms, two lists classes, two of everything.
I decided that it would be best to create an abstract base class for each control type that would hold almost all of the real logic, and then derived types to take care of the differences between the two components. However, the base classes would not have been able to perform operations on these components if I had to worry about types all of the time (well, they could have, but there would have been an "if" statement or switch in every method).
I defined a simple interface for these components and all of the base classes talk to this interface. Now when I change something, it pretty much 'just works' everywhere and I have no code duplication.
A lot of explanation out there, but to make it even more simpler. Take for instance a List. One can implement a list with as:
An internal array
A linked list
Other implementations
By building to an interface, say a List. You only code as to definition of List or what List means in reality.
You could use any type of implementation internally say an array implementation. But suppose you wish to change the implementation for some reason say a bug or performance. Then you just have to change the declaration List<String> ls = new ArrayList<String>() to List<String> ls = new LinkedList<String>().
Nowhere else in code, will you have to change anything else; Because everything else was built on the definition of List.
If you program in Java, JDBC is a good example. JDBC defines a set of interfaces but says nothing about the implementation. Your applications can be written against this set of interfaces. In theory, you pick some JDBC driver and your application would just work. If you discover there's a faster or "better" or cheaper JDBC driver or for whatever reason, you can again in theory re-configure your property file, and without having to make any change in your application, your application would still work.
I am a late comer to this question, but I want to mention here that the line "Program to an interface, not an implementation" had some good discussion in the GoF (Gang of Four) Design Patterns book.
It stated, on p. 18:
Program to an interface, not an implementation
Don't declare variables to be instances of particular concrete classes. Instead, commit only to an interface defined by an abstract class. You will find this to be a common theme of the design patterns in this book.
and above that, it began with:
There are two benefits to manipulating objects solely in terms of the interface defined by abstract classes:
Clients remain unaware of the specific types of objects they use, as long as the objects adhere to the interface that clients expect.
Clients remain unaware of the classes that implement these objects. Clients only know about the abstract class(es) defining the interface.
So in other words, don't write it your classes so that it has a quack() method for ducks, and then a bark() method for dogs, because they are too specific for a particular implementation of a class (or subclass). Instead, write the method using names that are general enough to be used in the base class, such as giveSound() or move(), so that they can be used for ducks, dogs, or even cars, and then the client of your classes can just say .giveSound() rather than thinking about whether to use quack() or bark() or even determine the type before issuing the correct message to be sent to the object.
Programming to Interfaces is awesome, it promotes loose coupling. As #lassevk mentioned, Inversion of Control is a great use of this.
In addition, look into SOLID principals. here is a video series
It goes through a hard coded (strongly coupled example) then looks at interfaces, finally progressing to a IoC/DI tool (NInject)
To add to the existing posts, sometimes coding to interfaces helps on large projects when developers work on separate components simultaneously. All you need is to define interfaces upfront and write code to them while other developers write code to the interface you are implementing.
It can be advantageous to program to interfaces, even when we are not depending on abstractions.
Programming to interfaces forces us to use a contextually appropriate subset of an object. That helps because it:
prevents us from doing contextually inappropriate things, and
lets us safely change the implementation in the future.
For example, consider a Person class that implements the Friend and the Employee interface.
class Person implements AbstractEmployee, AbstractFriend {
}
In the context of the person's birthday, we program to the Friend interface, to prevent treating the person like an Employee.
function party() {
const friend: Friend = new Person("Kathryn");
friend.HaveFun();
}
In the context of the person's work, we program to the Employee interface, to prevent blurring workplace boundaries.
function workplace() {
const employee: Employee = new Person("Kathryn");
employee.DoWork();
}
Great. We have behaved appropriately in different contexts, and our software is working well.
Far into the future, if our business changes to work with dogs, we can change the software fairly easily. First, we create a Dog class that implements both Friend and Employee. Then, we safely change new Person() to new Dog(). Even if both functions have thousands of lines of code, that simple edit will work because we know the following are true:
Function party uses only the Friend subset of Person.
Function workplace uses only the Employee subset of Person.
Class Dog implements both the Friend and Employee interfaces.
On the other hand, if either party or workplace were to have programmed against Person, there would be a risk of both having Person-specific code. Changing from Person to Dog would require us to comb through the code to extirpate any Person-specific code that Dog does not support.
The moral: programming to interfaces helps our code to behave appropriately and to be ready for change. It also prepares our code to depend on abstractions, which brings even more advantages.
If I'm writing a new class Swimmer to add the functionality swim() and need to use an object of class say Dog, and this Dog class implements interface Animal which declares swim().
At the top of the hierarchy (Animal), it's very abstract while at the bottom (Dog) it's very concrete. The way I think about "programming to interfaces" is that, as I write Swimmer class, I want to write my code against the interface that's as far up that hierarchy which in this case is an Animal object. An interface is free from implementation details and thus makes your code loosely-coupled.
The implementation details can be changed with time, however, it would not affect the remaining code since all you are interacting with is with the interface and not the implementation. You don't care what the implementation is like... all you know is that there will be a class that would implement the interface.
It is also good for Unit Testing, you can inject your own classes (that meet the requirements of the interface) into a class that depends on it
Short story: A postman is asked to go home after home and receive the covers contains (letters, documents, cheques, gift cards, application, love letter) with the address written on it to deliver.
Suppose there is no cover and ask the postman to go home after home and receive all the things and deliver to other people, the postman can get confused.
So better wrap it with cover (in our story it is the interface) then he will do his job fine.
Now the postman's job is to receive and deliver the covers only (he wouldn't bothered what is inside in the cover).
Create a type of interface not actual type, but implement it with actual type.
To create to interface means your components get Fit into the rest of code easily
I give you an example.
you have the AirPlane interface as below.
interface Airplane{
parkPlane();
servicePlane();
}
Suppose you have methods in your Controller class of Planes like
parkPlane(Airplane plane)
and
servicePlane(Airplane plane)
implemented in your program. It will not BREAK your code.
I mean, it need not to change as long as it accepts arguments as AirPlane.
Because it will accept any Airplane despite actual type, flyer, highflyr, fighter, etc.
Also, in a collection:
List<Airplane> plane; // Will take all your planes.
The following example will clear your understanding.
You have a fighter plane that implements it, so
public class Fighter implements Airplane {
public void parkPlane(){
// Specific implementations for fighter plane to park
}
public void servicePlane(){
// Specific implementatoins for fighter plane to service.
}
}
The same thing for HighFlyer and other clasess:
public class HighFlyer implements Airplane {
public void parkPlane(){
// Specific implementations for HighFlyer plane to park
}
public void servicePlane(){
// specific implementatoins for HighFlyer plane to service.
}
}
Now think your controller classes using AirPlane several times,
Suppose your Controller class is ControlPlane like below,
public Class ControlPlane{
AirPlane plane;
// so much method with AirPlane reference are used here...
}
Here magic comes as you may make your new AirPlane type instances as many as you want and you are not changing the code of ControlPlane class.
You can add an instance...
JumboJetPlane // implementing AirPlane interface.
AirBus // implementing AirPlane interface.
You may remove instances of previously created types too.
So, just to get this right, the advantage of a interface is that I can separate the calling of a method from any particular class. Instead creating a instance of the interface, where the implementation is given from whichever class I choose that implements that interface. Thus allowing me to have many classes, which have similar but slightly different functionality and in some cases (the cases related to the intention of the interface) not care which object it is.
For example, I could have a movement interface. A method which makes something 'move' and any object (Person, Car, Cat) that implements the movement interface could be passed in and told to move. Without the method every knowing the type of class it is.
Imagine you have a product called 'Zebra' that can be extended by plugins. It finds the plugins by searching for DLLs in some directory. It loads all those DLLs and uses reflection to find any classes that implement IZebraPlugin, and then calls the methods of that interface to communicate with the plugins.
This makes it completely independent of any specific plugin class - it doesn't care what the classes are. It only cares that they fulfill the interface specification.
Interfaces are a way of defining points of extensibility like this. Code that talks to an interface is more loosely coupled - in fact it is not coupled at all to any other specific code. It can inter-operate with plugins written years later by people who have never met the original developer.
You could instead use a base class with virtual functions - all plugins would be derived from the base class. But this is much more limiting because a class can only have one base class, whereas it can implement any number of interfaces.
C++ explanation.
Think of an interface as your classes public methods.
You then could create a template that 'depends' on these public methods in order to carry out it's own function (it makes function calls defined in the classes public interface). Lets say this template is a container, like a Vector class, and the interface it depends on is a search algorithm.
Any algorithm class that defines the functions/interface Vector makes calls to will satisfy the 'contract' (as someone explained in the original reply). The algorithms don't even need to be of the same base class; the only requirement is that the functions/methods that the Vector depends on (interface) is defined in your algorithm.
The point of all of this is that you could supply any different search algorithm/class just as long as it supplied the interface that Vector depends on (bubble search, sequential search, quick search).
You might also want to design other containers (lists, queues) that would harness the same search algorithm as Vector by having them fulfill the interface/contract that your search algorithms depends on.
This saves time (OOP principle 'code reuse') as you are able to write an algorithm once instead of again and again and again specific to every new object you create without over-complicating the issue with an overgrown inheritance tree.
As for 'missing out' on how things operate; big-time (at least in C++), as this is how most of the Standard TEMPLATE Library's framework operates.
Of course when using inheritance and abstract classes the methodology of programming to an interface changes; but the principle is the same, your public functions/methods are your classes interface.
This is a huge topic and one of the the cornerstone principles of Design Patterns.
In Java these concrete classes all implement the CharSequence interface:
CharBuffer, String, StringBuffer, StringBuilder
These concrete classes do not have a common parent class other than Object, so there is nothing that relates them, other than the fact they each have something to do with arrays of characters, representing such, or manipulating such. For instance, the characters of String cannot be changed once a String object is instantiated, whereas the characters of StringBuffer or StringBuilder can be edited.
Yet each one of these classes is capable of suitably implementing the CharSequence interface methods:
char charAt(int index)
int length()
CharSequence subSequence(int start, int end)
String toString()
In some cases, Java class library classes that used to accept String have been revised to now accept the CharSequence interface. So if you have an instance of StringBuilder, instead of extracting a String object (which means instantiating a new object instance), it can instead just pass the StringBuilder itself as it implements the CharSequence interface.
The Appendable interface that some classes implement has much the same kind of benefit for any situation where characters can be appended to an instance of the underlying concrete class object instance. All of these concrete classes implement the Appendable interface:
BufferedWriter, CharArrayWriter, CharBuffer, FileWriter, FilterWriter, LogStream, OutputStreamWriter, PipedWriter, PrintStream, PrintWriter, StringBuffer, StringBuilder, StringWriter, Writer
Previous answers focus on programming to an abstraction for the sake of extensibility and loose coupling. While these are very important points,
readability is equally important. Readability allows others (and your future self) to understand the code with minimal effort. This is why readability leverages abstractions.
An abstraction is, by definition, simpler than its implementation. An abstraction omits detail in order to convey the essence or purpose of a thing, but nothing more.
Because abstractions are simpler, I can fit a lot more of them in my head at one time, compared to implementations.
As a programmer (in any language) I walk around with a general idea of a List in my head at all times. In particular, a List allows random access, duplicate elements, and maintains order. When I see a declaration like this: List myList = new ArrayList() I think, cool, this is a List that's being used in the (basic) way that I understand; and I don't have to think any more about it.
On the other hand, I do not carry around the specific implementation details of ArrayList in my head. So when I see, ArrayList myList = new ArrayList(). I think, uh-oh, this ArrayList must be used in a way that isn't covered by the List interface. Now I have to track down all the usages of this ArrayList to understand why, because otherwise I won't be able to fully understand this code. It gets even more confusing when I discover that 100% of the usages of this ArrayList do conform to the List interface. Then I'm left wondering... was there some code relying on ArrayList implementation details that got deleted? Was the programmer who instantiated it just incompetent? Is this application locked into that specific implementation in some way at runtime? A way that I don't understand?
I'm now confused and uncertain about this application, and all we're talking about is a simple List. What if this was a complex business object ignoring its interface? Then my knowledge of the business domain is insufficient to understand the purpose of the code.
So even when I need a List strictly within a private method (nothing that would break other applications if it changed, and I could easily find/replace every usage in my IDE) it still benefits readability to program to an abstraction. Because abstractions are simpler than implementation details. You could say that programming to abstractions is one way of adhering to the KISS principle.
An interface is like a contract, where you want your implementation class to implement methods written in the contract (interface). Since Java does not provide multiple inheritance, "programming to interface" is a good way to achieve multiple inheritance.
If you have a class A that is already extending some other class B, but you want that class A to also follow certain guidelines or implement a certain contract, then you can do so by the "programming to interface" strategy.
Q: - ... "Could you use any class that implements an interface?"
A: - Yes.
Q: - ... "When would you need to do that?"
A: - Each time you need a class(es) that implements interface(s).
Note: We couldn't instantiate an interface not implemented by a class - True.
Why?
Because the interface has only method prototypes, not definitions (just functions names, not their logic)
AnIntf anInst = new Aclass();
// we could do this only if Aclass implements AnIntf.
// anInst will have Aclass reference.
Note: Now we could understand what happened if Bclass and Cclass implemented same Dintf.
Dintf bInst = new Bclass();
// now we could call all Dintf functions implemented (defined) in Bclass.
Dintf cInst = new Cclass();
// now we could call all Dintf functions implemented (defined) in Cclass.
What we have: Same interface prototypes (functions names in interface), and call different implementations.
Bibliography:
Prototypes - wikipedia
program to an interface is a term from the GOF book. i would not directly say it has to do with java interface but rather real interfaces. to achieve clean layer separation, you need to create some separation between systems for example: Let's say you had a concrete database you want to use, you would never "program to the database" , instead you would "program to the storage interface". Likewise you would never "program to a Web Service" but rather you would program to a "client interface". this is so you can easily swap things out.
i find these rules help me:
1. we use a java interface when we have multiple types of an object. if i just have single object, i dont see the point. if there are at least two concrete implementations of some idea, then i would use a java interface.
2. if as i stated above, you want to bring decoupling from an external system (storage system) to your own system (local DB) then also use a interface.
notice how there are two ways to consider when to use them.
Coding to an interface is a philosophy, rather than specific language constructs or design patterns - it instructs you what is the correct order of steps to follow in order to create better software systems (e.g. more resilient, more testable, more scalable, more extendible, and other nice traits).
What it actually means is:
===
Before jumping to implementations and coding (the HOW) - think of the WHAT:
What black boxes should make up your system,
What is each box' responsibility,
What are the ways each "client" (that is, one of those other boxes, 3rd party "boxes", or even humans) should communicate with it (the API of each box).
After you figure the above, go ahead and implement those boxes (the HOW).
Thinking first of what a box' is and what its API, leads the developer to distil the box' responsibility, and to mark for himself and future developers the difference between what is its exposed details ("API") and it's hidden details ("implementation details"), which is a very important differentiation to have.
One immediate and easily noticeable gain is the team can then change and improve implementations without affecting the general architecture. It also makes the system MUCH more testable (it goes well with the TDD approach).
===
Beyond the traits I've mentioned above, you also save A LOT OF TIME going this direction.
Micro Services and DDD, when done right, are great examples of "Coding to an interface", however the concept wins in every pattern from monoliths to "serverless", from BE to FE, from OOP to functional, etc....
I strongly recommend this approach for Software Engineering (and I basically believe it makes total sense in other fields as well).
Program to an interface allows to change implementation of contract defined by interface seamlessly. It allows loose coupling between contract and specific implementations.
IInterface classRef = new ObjectWhatever()
You could use any class that implements IInterface? When would you need to do that?
Have a look at this SE question for good example.
Why should the interface for a Java class be preferred?
does using an Interface hit performance?
if so how much?
Yes. It will have slight performance overhead in sub-seconds. But if your application has requirement to change the implementation of interface dynamically, don't worry about performance impact.
how can you avoid it without having to maintain two bits of code?
Don't try to avoid multiple implementations of interface if your application need them. In absence of tight coupling of interface with one specific implementation, you may have to deploy the patch to change one implementation to other implementation.
One good use case: Implementation of Strategy pattern:
Real World Example of the Strategy Pattern
"Program to interface" means don't provide hard code right the way, meaning your code should be extended without breaking the previous functionality. Just extensions, not editing the previous code.
Also I see a lot of good and explanatory answers here, so I want to give my point of view here, including some extra information what I noticed when using this method.
Unit testing
For the last two years, I have written a hobby project and I did not write unit tests for it. After writing about 50K lines I found out it would be really necessary to write unit tests.
I did not use interfaces (or very sparingly) ... and when I made my first unit test, I found out it was complicated. Why?
Because I had to make a lot of class instances, used for input as class variables and/or parameters. So the tests look more like integration tests (having to make a complete 'framework' of classes since all was tied together).
Fear of interfaces
So I decided to use interfaces. My fear was that I had to implement all functionality everywhere (in all used classes) multiple times. In some way this is true, however, by using inheritance it can be reduced a lot.
Combination of interfaces and inheritance
I found out the combination is very good to be used. I give a very simple example.
public interface IPricable
{
int Price { get; }
}
public interface ICar : IPricable
public abstract class Article
{
public int Price { get { return ... } }
}
public class Car : Article, ICar
{
// Price does not need to be defined here
}
This way copying code is not necessary, while still having the benefit of using a car as interface (ICar).

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.

What is the definition of "interface" in object oriented programming

A friend of mine goes back and forth on what "interface" means in programming.
What is the best description of an "interface"?
To me, an interface is a blueprint of a class. Is this the best definition?
An interface is one of the more overloaded and confusing terms in development.
It is actually a concept of abstraction and encapsulation. For a given "box", it declares the "inputs" and "outputs" of that box. In the world of software, that usually means the operations that can be invoked on the box (along with arguments) and in some cases the return types of these operations.
What it does not do is define what the semantics of these operations are, although it is commonplace (and very good practice) to document them in proximity to the declaration (e.g., via comments), or to pick good naming conventions. Nevertheless, there are no guarantees that these intentions would be followed.
Here is an analogy: Take a look at your television when it is off. Its interface are the buttons it has, the various plugs, and the screen. Its semantics and behavior are that it takes inputs (e.g., cable programming) and has outputs (display on the screen, sound, etc.). However, when you look at a TV that is not plugged in, you are projecting your expected semantics into an interface. For all you know, the TV could just explode when you plug it in. However, based on its "interface" you can assume that it won't make any coffee since it doesn't have a water intake.
In object oriented programming, an interface generally defines the set of methods (or messages) that an instance of a class that has that interface could respond to.
What adds to the confusion is that in some languages, like Java, there is an actual interface with its language specific semantics. In Java, for example, it is a set of method declarations, with no implementation, but an interface also corresponds to a type and obeys various typing rules.
In other languages, like C++, you do not have interfaces. A class itself defines methods, but you could think of the interface of the class as the declarations of the non-private methods. Because of how C++ compiles, you get header files where you could have the "interface" of the class without actual implementation. You could also mimic Java interfaces with abstract classes with pure virtual functions, etc.
An interface is most certainly not a blueprint for a class. A blueprint, by one definition is a "detailed plan of action". An interface promises nothing about an action! The source of the confusion is that in most languages, if you have an interface type that defines a set of methods, the class that implements it "repeats" the same methods (but provides definition), so the interface looks like a skeleton or an outline of the class.
Consider the following situation:
You are in the middle of a large, empty room, when a zombie suddenly attacks you.
You have no weapon.
Luckily, a fellow living human is standing in the doorway of the room.
"Quick!" you shout at him. "Throw me something I can hit the zombie with!"
Now consider:
You didn't specify (nor do you care) exactly what your friend will choose to toss;
...But it doesn't matter, as long as:
It's something that can be tossed (He can't toss you the sofa)
It's something that you can grab hold of (Let's hope he didn't toss a shuriken)
It's something you can use to bash the zombie's brains out (That rules out pillows and such)
It doesn't matter whether you get a baseball bat or a hammer -
as long as it implements your three conditions, you're good.
To sum it up:
When you write an interface, you're basically saying: "I need something that..."
Interface is a contract you should comply to or given to, depending if you are implementer or a user.
I don't think "blueprint" is a good word to use. A blueprint tells you how to build something. An interface specifically avoids telling you how to build something.
An interface defines how you can interact with a class, i.e. what methods it supports.
In Programming, an interface defines what the behavior a an object will have, but it will not actually specify the behavior. It is a contract, that will guarantee, that a certain class can do something.
Consider this piece of C# code here:
using System;
public interface IGenerate
{
int Generate();
}
// Dependencies
public class KnownNumber : IGenerate
{
public int Generate()
{
return 5;
}
}
public class SecretNumber : IGenerate
{
public int Generate()
{
return new Random().Next(0, 10);
}
}
// What you care about
class Game
{
public Game(IGenerate generator)
{
Console.WriteLine(generator.Generate())
}
}
new Game(new SecretNumber());
new Game(new KnownNumber());
The Game class requires a secret number. For the sake of testing it, you would like to inject what will be used as a secret number (this principle is called Inversion of Control).
The game class wants to be "open minded" about what will actually create the random number, therefore it will ask in its constructor for "anything, that has a Generate method".
First, the interface specifies, what operations an object will provide. It just contains what it looks like, but no actual implementation is given. This is just the signature of the method. Conventionally, in C# interfaces are prefixed with an I.
The classes now implement the IGenerate Interface. This means that the compiler will make sure, that they both have a method, that returns an int and is called Generate.
The game now is being called two different object, each of which implementant the correct interface. Other classes would produce an error upon building the code.
Here I noticed the blueprint analogy you used:
A class is commonly seen as a blueprint for an object. An Interface specifies something that a class will need to do, so one could argue that it indeed is just a blueprint for a class, but since a class does not necessarily need an interface, I would argue that this metaphor is breaking. Think of an interface as a contract. The class that "signs it" will be legally required (enforced by the compiler police), to comply to the terms and conditions in the contract. This means that it will have to do, what is specified in the interface.
This is all due to the statically typed nature of some OO languages, as it is the case with Java or C#. In Python on the other hand, another mechanism is used:
import random
# Dependencies
class KnownNumber(object):
def generate(self):
return 5
class SecretNumber(object):
def generate(self):
return random.randint(0,10)
# What you care about
class SecretGame(object):
def __init__(self, number_generator):
number = number_generator.generate()
print number
Here, none of the classes implement an interface. Python does not care about that, because the SecretGame class will just try to call whatever object is passed in. If the object HAS a generate() method, everything is fine. If it doesn't: KAPUTT!
This mistake will not be seen at compile time, but at runtime, so possibly when your program is already deployed and running. C# would notify you way before you came close to that.
The reason this mechanism is used, naively stated, because in OO languages naturally functions aren't first class citizens. As you can see, KnownNumber and SecretNumber contain JUST the functions to generate a number. One does not really need the classes at all. In Python, therefore, one could just throw them away and pick the functions on their own:
# OO Approach
SecretGame(SecretNumber())
SecretGame(KnownNumber())
# Functional Approach
# Dependencies
class SecretGame(object):
def __init__(self, generate):
number = generate()
print number
SecretGame(lambda: random.randint(0,10))
SecretGame(lambda: 5)
A lambda is just a function, that was declared "in line, as you go".
A delegate is just the same in C#:
class Game
{
public Game(Func<int> generate)
{
Console.WriteLine(generate())
}
}
new Game(() => 5);
new Game(() => new Random().Next(0, 10));
Side note: The latter examples were not possible like this up to Java 7. There, Interfaces were your only way of specifying this behavior. However, Java 8 introduced lambda expressions so the C# example can be converted to Java very easily (Func<int> becomes java.util.function.IntSupplier and => becomes ->).
To me an interface is a blueprint of a class, is this the best definition?
No. A blueprint typically includes the internals. But a interface is purely about what is visible on the outside of a class ... or more accurately, a family of classes that implement the interface.
The interface consists of the signatures of methods and values of constants, and also a (typically informal) "behavioral contract" between classes that implement the interface and others that use it.
Technically, I would describe an interface as a set of ways (methods, properties, accessors... the vocabulary depends on the language you are using) to interact with an object. If an object supports/implements an interface, then you can use all of the ways specified in the interface to interact with this object.
Semantically, an interface could also contain conventions about what you may or may not do (e.g., the order in which you may call the methods) and about what, in return, you may assume about the state of the object given how you interacted so far.
Personally I see an interface like a template. If a interface contains the definition for the methods foo() and bar(), then you know every class which uses this interface has the methods foo() and bar().
Let us consider a Man(User or an Object) wants some work to be done. He will contact a middle man(Interface) who will be having a contract with the companies(real world objects created using implemented classes). Few types of works will be defined by him which companies will implement and give him results.
Each and every company will implement the work in its own way but the result will be same. Like this User will get its work done using an single interface.
I think Interface will act as visible part of the systems with few commands which will be defined internally by the implementing inner sub systems.
An interface separates out operations on a class from the implementation within. Thus, some implementations may provide for many interfaces.
People would usually describe it as a "contract" for what must be available in the methods of the class.
It is absolutely not a blueprint, since that would also determine implementation. A full class definition could be said to be a blueprint.
An interface defines what a class that inherits from it must implement. In this way, multiple classes can inherit from an interface, and because of that inherticance, you can
be sure that all members of the interface are implemented in the derived class (even if its just to throw an exception)
Abstract away the class itself from the caller (cast an instance of a class to the interface, and interact with it without needing to know what the actual derived class IS)
for more info, see this http://msdn.microsoft.com/en-us/library/ms173156.aspx
In my opinion, interface has a broader meaning than the one commonly associated with it in Java. I would define "interface" as a set of available operations with some common functionality, that allow controlling/monitoring a module.
In this definition I try to cover both programatic interfaces, where the client is some module, and human interfaces (GUI for example).
As others already said, an interface always has some contract behind it, in terms of inputs and outputs. The interface does not promise anything about the "how" of the operations; it only guarantees some properties of the outcome, given the current state, the selected operation and its parameters.
As above, synonyms of "contract" and "protocol" are appropriate.
The interface comprises the methods and properties you can expect to be exposed by a class.
So if a class Cheetos Bag implements the Chip Bag interface, you should expect a Cheetos Bag to behave exactly like any other Chip Bag. (That is, expose the .attemptToOpenWithoutSpillingEverywhere() method, etc.)
A boundary across which two systems communicate.
Interfaces are how some OO languages achieve ad hoc polymorphism. Ad hoc polymorphism is simply functions with the same names operating on different types.
Conventional Definition - An interface is a contract that specifies the methods which needs to be implemented by the class implementing it.
The Definition of Interface has changed over time. Do you think Interface just have method declarations only ? What about static final variables and what about default definitions after Java 5.
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.
http://www.quora.com/Why-does-Java-allow-static-final-variables-in-interfaces-when-they-are-only-intended-to-be-contracts
In short, The basic problem an interface is trying to solve is to separate how we use something from how it is implemented. But you should consider interface is not a contract. Read more here.

Interface vs Base class

When should I use an interface and when should I use a base class?
Should it always be an interface if I don't want to actually define a base implementation of the methods?
If I have a Dog and Cat class. Why would I want to implement IPet instead of PetBase? I can understand having interfaces for ISheds or IBarks (IMakesNoise?), because those can be placed on a pet by pet basis, but I don't understand which to use for a generic Pet.
Let's take your example of a Dog and a Cat class, and let's illustrate using C#:
Both a dog and a cat are animals, specifically, quadruped mammals (animals are waaay too general). Let us assume that you have an abstract class Mammal, for both of them:
public abstract class Mammal
This base class will probably have default methods such as:
Feed
Mate
All of which are behavior that have more or less the same implementation between either species. To define this you will have:
public class Dog : Mammal
public class Cat : Mammal
Now let's suppose there are other mammals, which we will usually see in a zoo:
public class Giraffe : Mammal
public class Rhinoceros : Mammal
public class Hippopotamus : Mammal
This will still be valid because at the core of the functionality Feed() and Mate() will still be the same.
However, giraffes, rhinoceros, and hippos are not exactly animals that you can make pets out of. That's where an interface will be useful:
public interface IPettable
{
IList<Trick> Tricks{get; set;}
void Bathe();
void Train(Trick t);
}
The implementation for the above contract will not be the same between a cat and dog; putting their implementations in an abstract class to inherit will be a bad idea.
Your Dog and Cat definitions should now look like:
public class Dog : Mammal, IPettable
public class Cat : Mammal, IPettable
Theoretically you can override them from a higher base class, but essentially an interface allows you to add on only the things you need into a class without the need for inheritance.
Consequently, because you can usually only inherit from one abstract class (in most statically typed OO languages that is... exceptions include C++) but be able to implement multiple interfaces, it allows you to construct objects in a strictly as required basis.
Well, Josh Bloch said himself in Effective Java 2d:
Prefer interfaces over abstract classes
Some main points:
Existing classes can be easily retrofitted to implement a new
interface. All you have to do is add
the required methods if they don’t yet
exist and add an implements clause to
the class declaration.
Interfaces are ideal for defining mixins. Loosely speaking, a
mixin is a type that a class can
implement in addition to its “primary
type” to declare that it provides
some optional behavior. For example,
Comparable is a mixin interface that
allows a class to declare that its
instances are ordered with respect to
other mutually comparable objects.
Interfaces allow the construction of nonhierarchical type
frameworks. Type hierarchies are
great for organizing some things, but
other things don’t fall neatly into a
rigid hierarchy.
Interfaces enable safe, powerful functionality enhancements via the
wrap- per class idiom. If you use
abstract classes to define types, you
leave the programmer who wants to add
functionality with no alternative but
to use inheritance.
Moreover, you can combine the virtues
of interfaces and abstract classes by
providing an abstract skeletal
implementation class to go with each
nontrivial interface that you export.
On the other hand, interfaces are very hard to evolve. If you add a method to an interface it'll break all of it's implementations.
PS.: Buy the book. It's a lot more detailed.
Interfaces and base classes represent two different forms of relationships.
Inheritance (base classes) represent an "is-a" relationship. E.g. a dog or a cat "is-a" pet. This relationship always represents the (single) purpose of the class (in conjunction with the "single responsibility principle").
Interfaces, on the other hand, represent additional features of a class. I'd call it an "is" relationship, like in "Foo is disposable", hence the IDisposable interface in C#.
Modern style is to define IPet and PetBase.
The advantage of the interface is that other code can use it without any ties whatsoever to other executable code. Completely "clean." Also interfaces can be mixed.
But base classes are useful for simple implementations and common utilities. So provide an abstract base class as well to save time and code.
Interfaces
Most languages allow you to implement multiple interfaces
Modifying an interface is a breaking change. All implementations need to be recompiled/modified.
All members are public. Implementations have to implement all members.
Interfaces help in Decoupling. You can use mock frameworks to mock out anything behind an interface
Interfaces normally indicate a kind of behavior
Interface implementations are decoupled / isolated from each other
Base classes
Allows you to add some default implementation that you get for free by derivation (From C# 8.0 by interface you can have default implementation)
Except C++, you can only derive from one class. Even if could from multiple classes, it is usually a bad idea.
Changing the base class is relatively easy. Derivations do not need to do anything special
Base classes can declare protected and public functions that can be accessed by derivations
Abstract Base classes can't be mocked easily like interfaces
Base classes normally indicate type hierarchy (IS A)
Class derivations may come to depend on some base behavior (have intricate knowledge of parent implementation). Things can be messy if you make a change to the base implementation for one guy and break the others.
In general, you should favor interfaces over abstract classes. One reason to use an abstract class is if you have common implementation among concrete classes. Of course, you should still declare an interface (IPet) and have an abstract class (PetBase) implement that interface.Using small, distinct interfaces, you can use multiples to further improve flexibility. Interfaces allow the maximum amount of flexibility and portability of types across boundaries. When passing references across boundaries, always pass the interface and not the concrete type. This allows the receiving end to determine concrete implementation and provides maximum flexibility. This is absolutely true when programming in a TDD/BDD fashion.
The Gang of Four stated in their book "Because inheritance exposes a subclass to details of its parent's implementation, it's often said that 'inheritance breaks encapsulation". I believe this to be true.
This is pretty .NET specific, but the Framework Design Guidelines book argues that in general classes give more flexibility in an evolving framework. Once an interface is shipped, you don't get the chance to change it without breaking code that used that interface. With a class however, you can modify it and not break code that links to it. As long you make the right modifications, which includes adding new functionality, you will be able to extend and evolve your code.
Krzysztof Cwalina says on page 81:
Over the course of the three versions of the .NET Framework, I have talked about this guideline with quite a few developers on our team. Many of them, including those who initially disagreed with the guidelines, have said that they regret having shipped some API as an interface. I have not heard of even one case in which somebody regretted that they shipped a class.
That being said there certainly is a place for interfaces. As a general guideline always provide an abstract base class implementation of an interface if for nothing else as an example of a way to implement the interface. In the best case that base class will save a lot of work.
Juan,
I like to think of interfaces as a way to characterize a class. A particular dog breed class, say a YorkshireTerrier, may be a descended of the parent dog class, but it is also implements IFurry, IStubby, and IYippieDog. So the class defines what the class is but the interface tells us things about it.
The advantage of this is it allows me to, for example, gather all the IYippieDog's and throw them into my Ocean collection. So now I can reach across a particular set of objects and find ones that meet the criteria I am looking at without inspecting the class too closely.
I find that interfaces really should define a sub-set of the public behavior of a class. If it defines all the public behavior for all the classes that implement then it usually does not need to exist. They do not tell me anything useful.
This thought though goes counter to the idea that every class should have an interface and you should code to the interface. That's fine, but you end up with a lot of one to one interfaces to classes and it makes things confusing. I understand that the idea is it does not really cost anything to do and now you can swap things in and out with ease. However, I find that I rarely do that. Most of the time I am just modifying the existing class in place and have the exact same issues I always did if the public interface of that class needs changing, except I now have to change it in two places.
So if you think like me you would definitely say that Cat and Dog are IPettable. It is a characterization that matches them both.
The other piece of this though is should they have the same base class? The question is do they need to be broadly treated as the same thing. Certainly they are both Animals, but does that fit how we are going to use them together.
Say I want to gather all Animal classes and put them in my Ark container.
Or do they need to be Mammals? Perhaps we need some kind of cross animal milking factory?
Do they even need to be linked together at all? Is it enough to just know they are both IPettable?
I often feel the desire to derive a whole class hierarchy when I really just need one class. I do it in anticipation someday I might need it and usually I never do. Even when I do, I usually find I have to do a lot to fix it. That’s because the first class I am creating is not the Dog, I am not that lucky, it is instead the Platypus. Now my entire class hierarchy is based on the bizarre case and I have a lot of wasted code.
You might also find at some point that not all Cats are IPettable (like that hairless one). Now you can move that Interface to all the derivative classes that fit. You will find that a much less breaking change that all of a sudden Cats are no longer derived from PettableBase.
Here is the basic and simple definiton of interface and base class:
Base class = object inheritance.
Interface = functional inheritance.
cheers
It is explained well in this Java World article.
Personally, I tend to use interfaces to define interfaces - i.e. parts of the system design that specify how something should be accessed.
It's not uncommon that I will have a class implementing one or more interfaces.
Abstract classes I use as a basis for something else.
The following is an extract from the above mentioned article JavaWorld.com article, author Tony Sintes, 04/20/01
Interface vs. abstract class
Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks.
Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, Java calls the method defined by the child class.
Many developers forget that a class that defines an abstract method can call that method as well. Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies.
Class vs. interface
Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme. I use interfaces when I see that something in my design will change frequently.
For example, the Strategy pattern lets you swap new algorithms and processes into your program without altering the objects that use them. A media player might know how to play CDs, MP3s, and wav files. Of course, you don't want to hardcode those playback algorithms into the player; that will make it difficult to add a new format like AVI. Furthermore, your code will be littered with useless case statements. And to add insult to injury, you will need to update those case statements each time you add a new algorithm. All in all, this is not a very object-oriented way to program.
With the Strategy pattern, you can simply encapsulate the algorithm behind an object. If you do that, you can provide new media plug-ins at any time. Let's call the plug-in class MediaStrategy. That object would have one method: playStream(Stream s). So to add a new algorithm, we simply extend our algorithm class. Now, when the program encounters the new media type, it simply delegates the playing of the stream to our media strategy. Of course, you'll need some plumbing to properly instantiate the algorithm strategies you will need.
This is an excellent place to use an interface. We've used the Strategy pattern, which clearly indicates a place in the design that will change. Thus, you should define the strategy as an interface. You should generally favor interfaces over inheritance when you want an object to have a certain type; in this case, MediaStrategy. Relying on inheritance for type identity is dangerous; it locks you into a particular inheritance hierarchy. Java doesn't allow multiple inheritance, so you can't extend something that gives you a useful implementation or more type identity.
I recommend using composition instead of inheritence whenever possible. Use interfaces but use member objects for base implementation. That way, you can define a factory that constructs your objects to behave in a certain way. If you want to change the behavior then you make a new factory method (or abstract factory) that creates different types of sub-objects.
In some cases, you may find that your primary objects don't need interfaces at all, if all of the mutable behavior is defined in helper objects.
So instead of IPet or PetBase, you might end up with a Pet which has an IFurBehavior parameter. The IFurBehavior parameter is set by the CreateDog() method of the PetFactory. It is this parameter which is called for the shed() method.
If you do this you'll find your code is much more flexible and most of your simple objects deal with very basic system-wide behaviors.
I recommend this pattern even in multiple-inheritence languages.
Also keep in mind not to get swept away in OO (see blog) and always model objects based on behavior required, if you were designing an app where the only behavior you required was a generic name and species for an animal then you would only need one class Animal with a property for the name, instead of millions of classes for every possible animal in the world.
I have a rough rule-of-thumb
Functionality: likely to be different in all parts: Interface.
Data, and functionality, parts will be mostly the same, parts different: abstract class.
Data, and functionality, actually working, if extended only with slight changes: ordinary (concrete) class
Data and functionality, no changes planned: ordinary (concrete) class with final modifier.
Data, and maybe functionality: read-only: enum members.
This is very rough and ready and not at all strictly defined, but there is a spectrum from interfaces where everything is intended to be changed to enums where everything is fixed a bit like a read-only file.
Source: http://jasonroell.com/2014/12/09/interfaces-vs-abstract-classes-what-should-you-use/
C# is a wonderful language that has matured and evolved over the last 14 years. This is great for us developers because a mature language provides us with a plethora of language features that are at our disposal.
However, with much power becomes much responsibility. Some of these features can be misused, or sometimes it is hard to understand why you would choose to use one feature over another. Over the years, a feature that I have seen many developers struggle with is when to choose to use an interface or to choose to use an abstract class. Both have there advantages and disadvantages and the correct time and place to use each. But how to we decide???
Both provide for reuse of common functionality between types. The most obvious difference right away is that interfaces provide no implementation for their functionality whereas abstract classes allow you to implement some “base” or “default” behavior and then have the ability to “override” this default behavior with the classes derived types if necessary.
This is all well and good and provides for great reuse of code and adheres to the DRY (Don’t Repeat Yourself) principle of software development. Abstract classes are great to use when you have an “is a” relationship.
For example: A golden retriever “is a” type of dog. So is a poodle. They both can bark, as all dogs can. However, you might want to state that the poodle park is significantly different than the “default” dog bark. Therefor, it could make sense for you to implement something as follows:
public abstract class Dog
{
public virtual void Bark()
{
Console.WriteLine("Base Class implementation of Bark");
}
}
public class GoldenRetriever : Dog
{
// the Bark method is inherited from the Dog class
}
public class Poodle : Dog
{
// here we are overriding the base functionality of Bark with our new implementation
// specific to the Poodle class
public override void Bark()
{
Console.WriteLine("Poodle's implementation of Bark");
}
}
// Add a list of dogs to a collection and call the bark method.
void Main()
{
var poodle = new Poodle();
var goldenRetriever = new GoldenRetriever();
var dogs = new List<Dog>();
dogs.Add(poodle);
dogs.Add(goldenRetriever);
foreach (var dog in dogs)
{
dog.Bark();
}
}
// Output will be:
// Poodle's implementation of Bark
// Base Class implementation of Bark
//
As you can see, this would be a great way to keep your code DRY and allow for the base class implementation be called when any of the types can just rely on the default Bark instead of a special case implementation. The classes like GoldenRetriever, Boxer, Lab could all could inherit the “default” (bass class) Bark at no charge just because they implement the Dog abstract class.
But I’m sure you already knew that.
You are here because you want to understand why you might want to choose an interface over an abstract class or vice versa. Well one reason you may want to choose an interface over an abstract class is when you don’t have or want to prevent a default implementation. This is usually because the types that are implementing the interface not related in an “is a” relationship. Actually, they don’t have to be related at all except for the fact that each type “is able” or has “the ablity” to do something or have something.
Now what the heck does that mean? Well, for example: A human is not a duck…and a duck is not a human. Pretty obvious. However, both a duck and a human have “the ability” to swim (given that the human passed his swimming lessons in 1st grade :) ). Also, since a duck is not a human or vice versa, this is not an “is a” realationship, but instead an “is able” relationship and we can use an interface to illustrate that:
// Create ISwimable interface
public interface ISwimable
{
public void Swim();
}
// Have Human implement ISwimable Interface
public class Human : ISwimable
public void Swim()
{
//Human's implementation of Swim
Console.WriteLine("I'm a human swimming!");
}
// Have Duck implement ISwimable interface
public class Duck: ISwimable
{
public void Swim()
{
// Duck's implementation of Swim
Console.WriteLine("Quack! Quack! I'm a Duck swimming!")
}
}
//Now they can both be used in places where you just need an object that has the ability "to swim"
public void ShowHowYouSwim(ISwimable somethingThatCanSwim)
{
somethingThatCanSwim.Swim();
}
public void Main()
{
var human = new Human();
var duck = new Duck();
var listOfThingsThatCanSwim = new List<ISwimable>();
listOfThingsThatCanSwim.Add(duck);
listOfThingsThatCanSwim.Add(human);
foreach (var something in listOfThingsThatCanSwim)
{
ShowHowYouSwim(something);
}
}
// So at runtime the correct implementation of something.Swim() will be called
// Output:
// Quack! Quack! I'm a Duck swimming!
// I'm a human swimming!
Using interfaces like the code above will allow you to pass an object into a method that “is able” to do something. The code doesn’t care how it does it…All it knows is that it can call the Swim method on that object and that object will know which behavior take at run-time based on its type.
Once again, this helps your code stay DRY so that you would not have to write multiple methods that are calling the object to preform the same core function (ShowHowHumanSwims(human), ShowHowDuckSwims(duck), etc.)
Using an interface here allows the calling methods to not have to worry about what type is which or how the behavior is implemented. It just knows that given the interface, each object will have to have implemented the Swim method so it is safe to call it in its own code and allow the behavior of the Swim method be handled within its own class.
Summary:
So my main rule of thumb is use an abstract class when you want to implement a “default” functionality for a class hierarchy or/and the classes or types you are working with share a “is a” relationship (ex. poodle “is a” type of dog).
On the other hand use an interface when you do not have an “is a” relationship but have types that share “the ability” to do something or have something (ex. Duck “is not” a human. However, duck and human share “the ability” to swim).
Another difference to note between abstract classes and interfaces is that a class can implement one to many interfaces but a class can only inherit from ONE abstract class (or any class for that matter). Yes, you can nest classes and have an inheritance hierarchy (which many programs do and should have) but you cannot inherit two classes in one derived class definition (this rule applies to C#. In some other languages you are able to do this, usually only because of the lack of interfaces in these languages).
Also remember when using interfaces to adhere to the Interface Segregation Principle (ISP). ISP states that no client should be forced to depend on methods it does not use. For this reason interfaces should be focused on specific tasks and are usually very small (ex. IDisposable, IComparable ).
Another tip is if you are developing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
Hope this clears things up for some people!
Also if you can think of any better examples or want to point something out, please do so in the comments below!
Interfaces should be small. Really small. If you're really breaking down your objects, then your interfaces will probably only contain a few very specific methods and properties.
Abstract classes are shortcuts. Are there things that all derivatives of PetBase share that you can code once and be done with? If yes, then it's time for an abstract class.
Abstract classes are also limiting. While they give you a great shortcut to producing child objects, any given object can only implement one abstract class. Many times, I find this a limitation of Abstract classes, and this is why I use lots of interfaces.
Abstract classes may contain several interfaces. Your PetBase abstract class may implement IPet (pets have owners) and IDigestion (pets eat, or at least they should). However, PetBase will probably not implement IMammal, since not all pets are mammals and not all mammals are pets. You may add a MammalPetBase that extends PetBase and add IMammal. FishBase could have PetBase and add IFish. IFish would have ISwim and IUnderwaterBreather as interfaces.
Yes, my example is extensively over-complicated for the simple example, but that's part of the great thing about how interfaces and abstract classes work together.
The case for Base Classes over Interfaces was explained well in the Submain .NET Coding Guidelines:
Base Classes vs. Interfaces
An interface type is a partial
description of a value, potentially
supported by many object types. Use
base classes instead of interfaces
whenever possible. From a versioning
perspective, classes are more flexible
than interfaces. With a class, you can
ship Version 1.0 and then in Version
2.0 add a new method to the class. As long as the method is not abstract,
any existing derived classes continue
to function unchanged.
Because interfaces do not support
implementation inheritance, the
pattern that applies to classes does
not apply to interfaces. Adding a
method to an interface is equivalent
to adding an abstract method to a base
class; any class that implements the
interface will break because the class
does not implement the new method.
Interfaces are appropriate in the
following situations:
Several unrelated classes want to support the protocol.
These classes already have established base classes (for
example,
some are user interface (UI) controls,
and some are XML Web services).
Aggregation is not appropriate or practicable. In all other
situations,
class inheritance is a better model.
One important difference is that you can only inherit one base class, but you can implement many interfaces. So you only want to use a base class if you are absolutely certain that you won't need to also inherit a different base class. Additionally, if you find your interface is getting large then you should start looking to break it up into a few logical pieces that define independent functionality, since there's no rule that your class can't implement them all (or that you can define a different interface that just inherits them all to group them).
When I first started learning about object-oriented programming, I made the easy and probably common mistake of using inheritance to share common behavior - even where that behavior was not essential to the nature of the object.
To further build on an example much used in this particular question, there are lots of things that are petable - girlfriends, cars, fuzzy blankets... - so I might have had a Petable class that provided this common behavior, and various classes inheriting from it.
However, being petable is not part of the nature of any of these objects. There are vastly more important concepts that are essential to their nature - the girlfriend is a person, the car is a land vehicle, the cat is a mammal...
Behaviors should be assigned first to interfaces (including the default interface of the class), and promoted to a base class only if they are (a) common to a large group of classes that are subsets of a larger class - in the same sense that "cat" and "person" are subsets of "mammal".
The catch is, after you understand object-oriented design sufficiently better than I did at first, you'll normally do this automatically without even thinking about it. So the bare truth of the statement "code to an interface, not an abstract class" becomes so obvious you have a hard time believing anyone would bother to say it - and start trying to read other meanings into it.
Another thing I'd add is that if a class is purely abstract - with no non-abstract, non-inherited members or methods exposed to child, parent, or client - then why is it a class? It could be replaced, in some cases by an interface and in other cases by Null.
Prefer interfaces over abstract classes
Rationale,
the main points to consider [two already mentioned here] are :
Interfaces are more flexible, because a class can implement multiple
interfaces. Since Java does not have multiple inheritance, using
abstract classes prevents your users from using any other class
hierarchy. In general, prefer interfaces when there are no default
implementations or state. Java collections offer good examples of
this (Map, Set, etc.).
Abstract classes have the advantage of allowing better forward
compatibility. Once clients use an interface, you cannot change it;
if they use an abstract class, you can still add behavior without
breaking existing code. If compatibility is a concern, consider using
abstract classes.
Even if you do have default implementations or internal state,
consider offering an interface and an abstract implementation of it.
This will assist clients, but still allow them greater freedom if
desired [1].
Of course, the subject has been discussed at length
elsewhere [2,3].
[1] It adds more code, of course, but if brevity is your primary concern, you probably should have avoided Java in the first place!
[2] Joshua Bloch, Effective Java, items 16-18.
[3] http://www.codeproject.com/KB/ar...
Previous comments about using abstract classes for common implementation is definitely on the mark. One benefit I haven't seen mentioned yet is that the use of interfaces makes it much easier to implement mock objects for the purpose of unit testing. Defining IPet and PetBase as Jason Cohen described enables you to mock different data conditions easily, without the overhead of a physical database (until you decide it's time to test the real thing).
Don't use a base class unless you know what it means, and that it applies in this case. If it applies, use it, otherwise, use interfaces. But note the answer about small interfaces.
Public Inheritance is overused in OOD and expresses a lot more than most developers realize or are willing to live up to. See the Liskov Substitutablity Principle
In short, if A "is a" B then A requires no more than B and delivers no less than B, for every method it exposes.
Another option to keep in mind is using the "has-a" relationship, aka "is implemented in terms of" or "composition." Sometimes this is a cleaner, more flexible way to structure things than using "is-a" inheritance.
It may not make as much sense logically to say that Dog and Cat both "have" a Pet, but it avoids common multiple inheritance pitfalls:
public class Pet
{
void Bathe();
void Train(Trick t);
}
public class Dog
{
private Pet pet;
public void Bathe() { pet.Bathe(); }
public void Train(Trick t) { pet.Train(t); }
}
public class Cat
{
private Pet pet;
public void Bathe() { pet.Bathe(); }
public void Train(Trick t) { pet.Train(t); }
}
Yes, this example shows that there is a lot of code duplication and lack of elegance involved in doing things this way. But one should also appreciate that this helps to keep Dog and Cat decoupled from the Pet class (in that Dog and Cat do not have access to the private members of Pet), and it leaves room for Dog and Cat to inherit from something else--possibly the Mammal class.
Composition is preferable when no private access is required and you don't need to refer to Dog and Cat using generic Pet references/pointers. Interfaces give you that generic reference capability and can help cut down on the verbosity of your code, but they can also obfuscate things when they are poorly organized. Inheritance is useful when you need private member access, and in using it you are committing yourself to highly coupling your Dog and Cat classes to your Pet class, which is a steep cost to pay.
Between inheritance, composition, and interfaces there is no one way that is always right, and it helps to consider how all three options can be used in harmony. Of the three, inheritance is typically the option that should be used the least often.
Conceptually, an interface is used to formally and semi-formally define a set of methods that an object will provide. Formally means a set of method names and signatures, and semi-formally means human readable documentation associated with those methods.
Interfaces are only descriptions of an API (after all, API stands for application programming interface), they can't contain any implementation, and it's not possible to use or run an interface. They only make explicit the contract of how you should interact with an object.
Classes provide an implementation, and they can declare that they implement zero, one or more Interfaces. If a class is intended to be inherited, the convention is to prefix the class name with "Base".
There is a distinction between a base class and an abstract base classes (ABC). ABCs mix interface and implementation together. Abstract outside of computer programming means "summary", that is "abstract == interface". An abstract base class can then describe both an interface, as well as an empty, partial or complete implementation that is intended to be inherited.
Opinions on when to use interfaces versus abstract base classes versus just classes is going to vary wildly based on both what you are developing, and which language you are developing in. Interfaces are often associated only with statically typed languages such as Java or C#, but dynamically typed languages can also have interfaces and abstract base classes. In Python for example, the distinction is made clear between a Class, which declares that it implements an interface, and an object, which is an instance of a class, and is said to provide that interface. It's possible in a dynamic language that two objects that are both instances of the same class, can declare that they provide completely different interfaces. In Python this is only possible for object attributes, while methods are shared state between all objects of a class. However, in Ruby, objects can have per-instance methods, so it's possible that the interface between two objects of the same class can vary as much as the programmer desires (however, Ruby doesn't have any explicit way of declaring Interfaces).
In dynamic languages the interface to an object is often implicitly assumed, either by introspecting an object and asking it what methods it provides (look before you leap) or preferably by simply attempting to use the desired interface on an object and catching exceptions if the object doesn't provide that interface (easier to ask forgiveness than permission). This can lead to "false positives" where two interfaces have the same method name, but are semantically different. However, the trade-off is that your code is more flexible since you don't need to over specify up-front to anticipate all possible uses of your code.
It depends on your requirements. If IPet is simple enough, I would prefer to implement that. Otherwise, if PetBase implements a ton of functionality you don't want to duplicate, then have at it.
The downside to implementing a base class is the requirement to override (or new) existing methods. This makes them virtual methods which means you have to be careful about how you use the object instance.
Lastly, the single inheritance of .NET kills me. A naive example: Say you're making a user control, so you inherit UserControl. But, now you're locked out of also inheriting PetBase. This forces you to reorganize, such as to make a PetBase class member, instead.
I usually don't implement either until I need one. I favor interfaces over abstract classes because that gives a little more flexibility. If there's common behavior in some of the inheriting classes I move that up and make an abstract base class. I don't see the need for both, since they essentially server the same purpose, and having both is a bad code smell (imho) that the solution has been over-engineered.
Regarding C#, in some senses interfaces and abstract classes can be interchangeable. However, the differences are: i) interfaces cannot implement code; ii) because of this, interfaces cannot call further up the stack to subclass; and iii) only can abstract class may be inherited on a class, whereas multiple interfaces may be implemented on a class.
By def, interface provides a layer to communicate with other code. All the public properties and methods of a class are by default implementing implicit interface. We can also define an interface as a role, when ever any class needs to play that role, it has to implement it giving it different forms of implementation depending on the class implementing it. Hence when you talk about interface, you are talking about polymorphism and when you are talking about base class, you are talking about inheritance. Two concepts of oops !!!
I've found that a pattern of Interface > Abstract > Concrete works in the following use-case:
1. You have a general interface (eg IPet)
2. You have a implementation that is less general (eg Mammal)
3. You have many concrete members (eg Cat, Dog, Ape)
The abstract class defines default shared attributes of the concrete classes, yet enforces the interface. For example:
public interface IPet{
public boolean hasHair();
public boolean walksUprights();
public boolean hasNipples();
}
Now, since all mammals have hair and nipples (AFAIK, I'm not a zoologist), we can roll this into the abstract base class
public abstract class Mammal() implements IPet{
#override
public walksUpright(){
throw new NotSupportedException("Walks Upright not implemented");
}
#override
public hasNipples(){return true}
#override
public hasHair(){return true}
And then the concrete classes merely define that they walk upright.
public class Ape extends Mammal(){
#override
public walksUpright(return true)
}
public class Catextends Mammal(){
#override
public walksUpright(return false)
}
This design is nice when there are lots of concrete classes, and you don't want to maintain boilerplate just to program to an interface. If new methods were added to the interface, it would break all of the resulting classes, so you are still getting the advantages of the interface approach.
In this case, the abstract could just as well be concrete; however, the abstract designation helps to emphasize that this pattern is being employed.
An inheritor of a base class should have an "is a" relationship. Interface represents An "implements a" relationship.
So only use a base class when your inheritors will maintain the is a relationship.
Use Interfaces to enforce a contract ACROSS families of unrelated classes. For example, you might have common access methods for classes that represent collections, but contain radically different data i.e. one class might represent a result set from a query, while the other might represent the images in a gallery. Also, you can implement multiple interfaces, thus allowing you to blend (and signify) the capabilities of the class.
Use Inheritance when the classes bear a common relationship and therefore have a similair structural and behavioural signature, i.e. Car, Motorbike, Truck and SUV are all types of road vehicle that might contain a number of wheels, a top speed

Why can't I seem to grasp interfaces?

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.