What's the difference between an interface and an abstract class? [duplicate] - oop

This question already has answers here:
Closed 13 years ago.
Duplicate:
When to use an interface instead of an abstract class and vice versa?
Probably one of the most famous software developer job interview questions.
What would be your answer?
EDIT: I'm trying to find out how you would answer this in a real-life situation. Please try to formulate your answer as you would on a real job interview (be complete, but don't be too long, post no links of course).

An interface only describes the actual signature of its methods etc. Any class implementing that interface must then provide an explicit implementation.
An abstract class can contain a partial implementation of its methods etc.

An abstract class can have member variables, an interface cannot (or, in C++, should not).
In Java, an "Interface" is a well-defined syntactical element, while in C++ it's merely a design pattern.

Interfaces provide definitions of methods that must be implemented by a class. The purpose of interfaces is to allow you to generalise specific functionality regardless of implementation. You may have an IDatabase interface that has an Open/Close method. The class that implements that interface may be connecting to a MySQL database or MS Access database. Irrespective of how it accomplishes this task, the goal is still the same...Open database, close database.
Abstract classes are base classes that contain some abstract methods. They cannot be instantiated they are to be derived from. The purpose of an Abstract class is to allow you to define some generic functionality and sub-class to implement more specific functionality where appropriate.
So in summary, you should use interfaces when the implementation of each class differs completely. Use abstract classes when you have some similar behaviour but need to implement parts differently.
Hope that helps.

I would say that the difference is language dependent, but that in C++ at least, abstract classes are the means by which interfaces are implemented.

As far as job interviews are concerned, I've always heard that the key point is that an interface is a contract; an interface, while not implementing it itself, guarantees functionality.

Related

Is it good practice for every public method to be covered by an interface?

It's good practice for a class' implementation to be defined by interfaces. If a class has any public methods that aren't covered by any interfaces then they have the potential to leak their implementation.
E.g. if class Foo has methods bar() and baz() but only bar() is covered by an interface then any use of baz() doesn't use an interface.
It feels like to get cleaner code it would make sense to either:
create extra interfaces if the class has to have those methods (eg a separate interface to cover the behavior of baz() above)
or ideally refactor (eg using more composition) so the class doesn't need to have so many methods (put baz() in another class)
Having methods not covered by an interface feels like a code smell. Or am I being unrealistic?
I consider it as "overusing" the interface.
Interface can give you access only to limited functionality, therefore it is good for gathering more classes with similar functionality into one List<Interface> and using them, for example.
Or if you want to keep loose coupling principle, you rather give another component some interface than the whole class(es).
Also some classes should have restricted access to another classes, which can be done with interfaces too.
However high cohesion principle (which is usually connected to loose coupling) does not prevent you from using class itself, if two classes are and should be "strong" connected to each other.
I don't think that's the purpose of interfaces. If you actually talk about the 'is-a' and 'has-a' relationship between classes, not necessarily a class needs to cover all public methods in interfaces. That's like taking the concept too far.
A class can have methods which describe it's behavior but then, there are some methods that do not exactly describe the classes' behavior but rather describe what else the class can do.
In case if a question arises about SRP regarding the 'can-do' behaviors, it is possible that the class can use a component to execute those behaviors rather than implementing within itself.
For e.g., I have a class DataGrid, why would I need to have an interface called IDataGrid which exposes all the public methods. But may be there is an additional functionality that the DataGrid can do, which is export the data. In that case I can have it implement IExportData, and implement the ExportData method, which in turn does not export the data but uses a component, say DataExportHelper, that actually does the job.
The DataGrid only passes the data to the component.
I don't think SRP will be violated in the above example.
EDIT:
I am a .Net developer, so would like to give you and example from MS library classes. For e.g., the class System.Windows.Window does not implemnt any interface that has Close() method. And I don't see why it should be a part of any presenter.
Also, it is possible that something might look seem like a code smell but not necessarily it might be wrong. Code smell itself does not mean there is a problem but that there is a possibility of problem.
I have never come across any principle or guideline in software design which mentions that all the public members of a class need to be exposed in some or the other interface. May be doing that just for the sake of it might be a bad design.
No, I would definitely not consider methods not covered by an interface a code smell.
It seems like this might be dependent on the object infrastructure you are building in, but in the infrastructures I'm familiar with, the real point of interfaces is to provide a manageable form of multiple inheritance. I consider the overuse of multiple inheritance a notable smell.
In .NET at least, abstract classes are explicitly the preferred construct for exposing abstraction (not interfaces). The .NET design guidelines say: Do favor defining classes over interfaces., with rationale described here http://msdn.microsoft.com/en-us/library/vstudio/ms229013(v=vs.100).aspx.
Even in COM (where any externally visible functionality had to be defined in an interface) there are perfectly good reasons to have non-exposed functions: limiting the visibility of implementation details. COM was originally defined in C (not C++) which lacked the richer set of access modifiers that newer languages have, but the concepts were there: published interface members were public, everything else was internal.

Are interfaces redundant if using abstracts as an interface?

I'm reading through Design Patterns by GoF and I'm starting to wonder. Are interfaces redundant if you're using an abstract as the interface in languages like C#? Let's put multiple inheritance aside for a moment, as I understand you can only achieve that (in C#) through interfaces.
I'm trying to apply this logic to DDD in C#. Almost every example and implementation I've ever seen uses interfaces. I'm starting to wonder why. Could the abstract class be used instead? It seems to me that this would be a more robust solution, but then again I could be missing something, which is why I'm asking here.
Summary:
Question 1: In the context of OOP with a language that only supports single inheritance, if designed properly what are some uses
of interfaces over the abstract class?
Question 2: In the context of DDD, if designed properly what are the uses of interfaces over the abstract class?
Note:
I've read through all the similar questions listed, but none seem to give me an answer. If I missed one, please let me know.
For question 1: regardless of support for multiple inheritance interfaces are contract specifications, abstract classes are base classes.
Interfaces provide a way for a class to specify a set of capabilities ( think IDisposable, IEnumerable, etc ) and it's recommended that they obey the Interface Segregation Principle.
Abstract classes should implement a concept that can be extended, or that can have different implementations depending on the context ( think HttpContextBase, AbstractButton etc ).
The biggest difference between interfaces and abstract classes is conceptual. You can argue that, except inheritance, an interface is the same as an abstract class with only abstract methods, but conceptually they represent different things.
As for question 2: in the context of DDD interfaces are implementations details. I dare say you can do DDD and not use interfaces or abstract classes, or even inheritance. As long as you have your bounded contexts, aggregates, entities and VOs well defined.
In conclusion, when you try to express a contract use an interface, when you want to indicate that your class has some capability, implement an interface. When you have a concept for which you can provide more implementations depending on context, use a base class ( abstract or not ).
When you think about it like this, the decision of the language makers ( c# ) to allow only single inheritance, but allow implementation of multiple interfaces makes a lot of sense.
The advantage of Interfaces is precisely that there is no multiple-inheritance. By using an Interface you can allow classes like Forms, UserControls, Components, etc to participate in interactions that would otherwise be diffucult/impossible.
I recommend doing both. I usually create an interface, and (if possible) then create an abstract class that inherits that interface to provde any common or default implementaion of that interface. This gives you the best of both worlds.
interfaces are not redundant. an interface is independent of implementation while abstract classes are implementation. code that uses an interface does not have to be changed or recompiled if some implementation class changes.
the advantage is above. if you are doing ddd, start out with concrete classes and write some tests. refactor common stuff into base classes (some will be abstract). if there is a reason to make an interface go ahead and do so. repeat until done.

Interface uses as like this

If interfaces have empty methods (implicit abstract method) then what is its use? Why do we say it reduces the code and provides re-usability? Give me a real life example of using an interface that shows the difference between an abstract class and an interface.
Interface is more like a contract. It doesn't provide any implementation reuse as such. Which actually makes your code de-coupled from implementation. Having a abstract class with ALL the methods abstract provides the same benefit (if we ignore the issue of multiple inheritance).
For a really good example take a look at Java Collections and how things are loosely coupled using interfaces for Collection, Map and Lists.
Because of the terminology you are using, I am going to assume you are talking about Java.
An interface is useful in lieu of an abstract class because a class can only inherit from a single class, but can implement multiple interfaces.
An interface is a contract between parts of the program. It says that one part of the program has certain expectations about classes that implement this interface. As long as those classes uphold that interface contract, the other parts of the program don't care how that contract is implemented, just that it is implemented.
It allows for polymorphism and for the reuse of code. For instance, (with respect to Java), you can take the List interface. You can write code that interfaces with a List object where you don't care about the implementation of the List. Your code then can be used with a LinkedList or an ArrayList or any other type of list that it may deal with, and it should be able to manage well enough. You can write code now that has certain expectations through this List interface contract, and 15 years down the road someone can use the latest technologies to create their own List implementation and your code will be able to use it.
Abstract class lets you describe fields and non abstract methods. It does not limit you to simply describing interface, it involves some logic. Interface on other hand does what it says and has nothing to do with logic. From client code side, you have no worries about implementation and how stuff works. It lets you exchange one interface realization with other without additional code.
On realization code side, interface lets you perform multiple "inheritance".
I like to call these types of features "implied code documentation". Using an interface can communicate a lot of information to other developers who will be working on your project, and this information can help prevent a lot of headaches.
For instance, if a class implements an interface that has 2 methods, and I'm new to the project, that may tell me that the developer who wrote those methods don't want the method signature to change.
Think about the Dog class and the Cat class that both implement the interface Sociable, where there are methods walk(int speed), sit(), layDown(), bite(int degree).
If we have a Dog class and a Cat class that implement these methods and there are dependencies on them, changing the method signature of one could have some negative effects.
Interfaces are a way to help describe a class. In this example, a Sociable Dog and a Sociable Cat have a lot in common.
As far as reusability goes, your classes become reusable because it's harder for others to come in and change the contract defined in the method signature.
Lastly, while a class can only subclass one class, it can implement multiple interfaces. Thus, the advantage of using an interface is that I can have a Dog that implements Big and Sociable, and a Cat that implements Small and Sociable.

When to use interfaces or abstract classes? When to use both?

While certain guidelines state that you should use an interface when you want to define a contract for a class where inheritance is not clear (IDomesticated) and inheritance when the class is an extension of another (Cat : Mammal, Snake : Reptile), there are cases when (in my opinion) these guidelines enter a gray area.
For example, say my implementation was Cat : Pet. Pet is an abstract class. Should that be expanded to Cat : Mammal, IDomesticated where Mammal is an abstract class and IDomesticated is an interface? Or am I in conflict with the KISS/YAGNI principles (even though I'm not sure whether there will be a Wolf class in the future, which would not be able to inherit from Pet)?
Moving away from the metaphorical Cats and Pets, let's say I have some classes that represent sources for incoming data. They all need to implement the same base somehow. I could implement some generic code in an abstract Source class and inherit from it. I could also just make an ISource interface (which feels more "right" to me) and re-implement the generic code in each class (which is less intuitive). Finally, I could "have the cake and eat it" by making both the abstract class and the interface. What's best?
These two cases bring up points for using only an abstract class, only an interface and using both an abstract class and an interface. Are these all valid choices, or are there "rules" for when one should be used over another?
I'd like to clarify that by "using both an abstract class and an interface" that includes the case when they essentially represent the same thing (Source and ISource both have the same members), but the class adds generic functionality while the interface specifies the contract.
Also worth noting is that this question is mostly for languages that do not support multiple inheritance (such as .NET and Java).
As a first rule of thumb, I prefer abstract classes over interfaces, based on the .NET Design Guidelines. The reasoning applies much wider than .NET, but is better explained in the book Framework Design Guidelines.
The main reasoning behind the preference for abstract base classes is versioning, because you can always add a new virtual member to an abstract base class without breaking existing clients. That's not possible with interfaces.
There are scenarios where an interface is still the correct choice (particularly when you don't care about versioning), but being aware of the advantages and disadvantages enables you to make the correct decision.
So as a partial answer before I continue: Having both an interface and a base class only makes sense if you decide to code against an interface in the first place. If you allow an interface, you must code against that interface only, since otherwise you would be violating the Liskov Substitution Principle. In other words, even if you provide a base class that implements the interface, you cannot let your code consume that base class.
If you decide to code against a base class, having an interface makes no sense.
If you decide to code against an interface, having a base class that provides default functionality is optional. It is not necessary, but may speed up things for implementers, so you can provide one as a courtesy.
An example that springs to mind is in ASP.NET MVC. The request pipeline works on IController, but there's a Controller base class that you typically use to implement behavior.
Final answer: If using an abstract base class, use only that. If using an interface, a base class is an optional courtesy to implementers.
Update: I no longer prefer abstract classes over interfaces, and I haven't for a long time; instead, I favour composition over inheritance, using SOLID as a guideline.
(While I could edit the above text directly, it would radically change the nature of the post, and since a few people have found it valuable enough to up-vote it, I'd rather let the original text stand, and instead add this note. The latter part of the post is still meaningful, so it would be a shame to delete it, too.)
I tend to use base classes (abstract or not) to describe what something is, while I use interfaces to describe the capabilities of an object.
A Cat is a Mammal but one of it's capabilities is that it is Pettable.
Or, to put it a different way, classes are nouns, while interfaces map closer to adjectives.
From MSDN, Recommendations for Abstract Classes vs. Interfaces
If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.
If you want to provide the option of replacing your implementation completely, use an interface. This applies especially for interactions between major components, these should always be decoupled by interfaces.
There may also be technical reasons for prefering an interface, for example to enable mocking in unit tests.
Internally in a component it may be fine to just use an abstract class directly to access a hierarchy of classes.
If you use an interface and have a hierarchy of implementing classes then it is good practice to have an abstract classe which contain the common parts of the implementation. E.g.
interface Foo
abstract class FooBase implements Foo
class FunnyFoo extends FooBase
class SeriousFoo extends FooBase
You could also have more abstract classes inheriting from each other for a more complicated hierarchy.
Refer to below SE question for generic guidelines:
Interface vs Abstract Class (general OO)
Practical use case for interface:
Implementation of Strategy_pattern: Define your strategy as an interface. Switch the implementation dynamically with one of concrete implementations of strategy at run time.
Define a capability among multiple unrelated classes.
Practical use case for abstract class:
Implementation of Template_method_pattern: Define a skeleton of an algorithm. The child classes can't change strucutre of the algortihm but they can re-define a part of the implementation in child classes.
When you want share non-static and non-final variables among multiple related classes with "has a" relation.
Use of both abstradt class and interface:
If you are going for an abstract class, you can move abstract methods to interface and abstract class can simply implement that interface. All use cases of abstract classes can fall into this category.
I always use these guidelines:
Use interfaces for multiple TYPE inheritance (as .NET/Java don't use multiple inheritance)
Use abstract classes for a re-usable implementation of a type
The rule of the dominant concern dictates that a class always has a main concern and 0 or more others (see http://citeseer.ist.psu.edu/tarr99degrees.html). Those 0 or more others you then implement through interfaces, as the class then implements all the types it has to implement (its own, and all interfaces it implements).
In a world of multiple implementation inheritance (e.g. C++/Eiffel), one would inherit from classes which implement the interfaces. (In theory. In practise it might not work that well.)
There is also something called the DRY principle - Don't Repeat Yourself.
In your example of data sources you say there is some generic code that is common between different implementations. To me it seems that the best way to handle that would be to have an abstract class with the generic code in it and some concrete classes extending it.
The advantage is that every bug fix in generic code benefits all concrete implementations.
If you go interface only you will have to maintain several copies of the same code which is asking for trouble.
Regarding abstract + interface if there is no immediate justification for it I would not do it. Extracting interface from abstract class is an easy refactoring, so I would do it only when it is actually needed.

Description of what an interface does? [duplicate]

This question already has answers here:
Why can't I seem to grasp interfaces?
(26 answers)
Closed 3 years ago.
With regards to OOP, how would you describe an interface?
What I mean is, sub-classing can be described as "Has-A", and inheritance could be "Is-A". A member method could be "Can-Do".
Is there any way this could be extended (no pun intended) to describe what an interface does?
I think of objects as nouns, methods as verbs, and interfaces as adjectives (of course this analogy is oversimplified, but frequently works well enough).
Example: an interface Serializable works like an adjective, in that it applies some qualities to an object that implement that interface, but does not change what that object is. We can say, "this is a serializable object." But we don't say, "this object is a serializable," nor do we say, "this object has a serializable."
I also like Federico's answer that an interface is "CAN-DO".
An interface is a group of related operations that the class supports. Together, the methods in an interface describe what the class can do.
Just like a noun can take multiple adjectives, a class can implement multiple interfaces, as long as they don't conflict. The union of all the interfaces a class implements is the sum of what the class can do.
In practical terms, an interface is a set of method signatures, without the code implementing those methods. Just the method name and arguments. Depending on the language, a method signature may also include return type, and exceptions thrown.
An interface consists of methods, but not data members.
BTW, I wouldn't say sub-classing is HAS-A. My understanding is that sub-classing is the same as inheritance, so these are both IS-A. Whereas HAS-A is called Aggregation or Composition.
Composition is where an object owns another object. Destroying the outer object also destroys the inner objects. Example: University composes Departments. Close the University, and the Departments disappear.
Aggregation is where an object includes another object, but does not own it. Destroying the outer object does not destroy the inner objects. Example: University employs Professors, but closing the University does not kill the Professors.
An interface is an abstract base class with all pure virtual members.
So looking at your Has-A/Is-A, it should be similar to whatever you would be apply for an abstract base class.
Interfaces generally exist in languages that do not fully support multiple inheritance as a way to more safely offer some of the same benefits.
Acts-As-A.
As is your description for methods, I would also describe an interface as a "Can-Do". An interface is a contract like "all the classes that implement me, can do these things".
Joel that isn't exaclty what an interface is. It is like a abstract base class in a way but it has no implementation of the methods and properties.
This pretty much sums up what an interface is.
http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_interrfaces03052006095933AM/csharp_interrfaces.aspx?ArticleID=cd6a6952-530a-4250-a6d7-54717ef3b345