Interface vs Abstract Class (general OO)
Asked Answered
C

34

1558

I have recently had two telephone interviews where I've been asked about the differences between an Interface and an Abstract class. I have explained every aspect of them I could think of, but it seems they are waiting for me to mention something specific, and I don't know what it is.

From my experience I think the following is true. If I am missing a major point please let me know.

Interface:

Every single Method declared in an Interface will have to be implemented in the subclass. Only Events, Delegates, Properties (C#) and Methods can exist in an Interface. A class can implement multiple Interfaces.

Abstract Class:

Only Abstract methods have to be implemented by the subclass. An Abstract class can have normal methods with implementations. An Abstract class can also have class variables besides Events, Delegates, Properties and Methods. A class can implement one abstract class only due to the non-existence of Multi-inheritance in C#.

  1. After all that, the interviewer came up with the question "What if you had an Abstract class with only abstract methods? How would that be different from an interface?" I didn't know the answer but I think it's the inheritance as mentioned above right?

  2. Another interviewer asked me, "What if you had a Public variable inside the interface, how would that be different than in a Abstract Class?" I insisted you can't have a public variable inside an interface. I didn't know what he wanted to hear but he wasn't satisfied either.

See Also:

Canebrake answered 17/4, 2009 at 16:42 Comment(20)
While I think it's important to know the difference between the two, this isn't a good interview question, imo. Unless the job was writing a book on OO topics. You're better off not working for those ding bats.Hartzog
@Alan: I actually like this as an interview question, but I wouldn't hound somebody this way about it - I'd probably post it more like "Where would you choose an interface over an abstract base class, when defining a hierarchy?", or something similar.Durning
Maybe they were after a more design focused answer... though like you I would have treated it as a technical question.Offing
Nice tabular differences here: mindprod.com/jgloss/interfacevsabstract.htmlCleocleobulus
They may have been fishing for an answer of when or why you would use one over the other. That is what would truly display whether or not you get it - instead of just being able to define them.Baryta
"if you had a Public variable inside the interface, how would that be different than in Abstract Class?" Sounds to me that the interviewer was at least confused regarding the topic. You shouldn't worry what was that they wanted to hear, they should.Stamin
stackoverflow.com/questions/1913098/…Earthshaking
stackoverflow.com/questions/4756065/…Mononuclear
@Kave: I insisted you can't have a public variable inside an interface. I think interface can have public variable. In fact variables in interface are automatically public and final.Wine
Considering about how you would test these may shed some light on yuor thinking https://mcmap.net/q/16133/-how-to-unit-test-abstract-classes-extend-with-stubsCatamenia
I regularly ask this question in phone screen interviews. It weeds out people who don't know the basics of programming. I'd move on after the answer given in the question. In a phone screen, my goal really is to weed out the people who will waste my time in F2F, and this question is very effective.Tilley
@a Learner: If we're talking C#, an interface with a field results in the compile-error, Interfaces cannot contain fields. C# interfaces may contain properties, not fields (i.e., variables).Haggis
This is an extremely very common question on interviews. It is surprising since abstract classes are rarely used in solutions compared to other things people could ask about.Izaguirre
This question might help to understand concept of interfaces. https://mcmap.net/q/23159/-why-to-use-interfaces-multiple-inheritance-vs-interfaces-benefits-of-interfaces/1055241Pantia
possible duplicate of When to use an interface instead of an abstract class and vice versa?Upside
1. Abstract classes are part of the Interitance tree. That's what makes it different from Interfaces. 2. All the variables are by default "Public final" in an interface. Abstract classes can have anything.Dianoia
IMO, the interview questions are really very good. In order to answer those questions, you really need to understand the complete set of differences and usage of Abstract class & Interface, their advantages and limitations.Undermanned
Does this answer your question? What is the difference between an interface and abstract class?Railey
I insisted you can't have a public variable inside an interface. that's what an interface is for, for public consumptionAmoral
Abtract classes can have non empty methods shared across the child classes.Deception
H
807

While your question indicates it's for "general OO", it really seems to be focusing on .NET use of these terms.

In .NET (similar for Java):

  • interfaces can have no state or implementation
  • a class that implements an interface must provide an implementation of all the methods of that interface
  • abstract classes may contain state (data members) and/or implementation (methods)
  • abstract classes can be inherited without implementing the abstract methods (though such a derived class is abstract itself)
  • interfaces may be multiple-inherited, abstract classes may not (this is probably the key concrete reason for interfaces to exist separately from abtract classes - they permit an implementation of multiple inheritance that removes many of the problems of general MI).

As general OO terms, the differences are not necessarily well-defined. For example, there are C++ programmers who may hold similar rigid definitions (interfaces are a strict subset of abstract classes that cannot contain implementation), while some may say that an abstract class with some default implementations is still an interface or that a non-abstract class can still define an interface.

Indeed, there is a C++ idiom called the Non-Virtual Interface (NVI) where the public methods are non-virtual methods that 'thunk' to private virtual methods:

Hyder answered 17/4, 2009 at 17:18 Comment(11)
Thank you. I think since your answer mentions state + a good overview of all rest, i mark your response as a final answer. You are right I asked for general OO, since my first interviewer asked for general OO, but since I am a C# guy, I tend to forget that. ;-) Also thanks for the C++ explanation, as always c++ is mind blowing.Canebrake
I think a key point in the explanation Michael provided is that when implementing an interface you MUST implement all members in the interface, but when inheriting from an abstract class it's NOT REQUIRED by a child class to implement its parent's membersRavens
+1: I'd be willing to bet that those monkeys hosting the interview don't even realise that other languages implement OO differently.Fluorene
@MichaelBurr Michael, in this MSDN article they state that "Abstract methods have no implementation" which conflicts with one of your bullet points. Are there exceptions to their rule or has the rule changed?Desertion
@JL I don't see where the problem lies. You seem to have confused abstract method with abstract class. Abstract methods have no implementation. However, inside of an abstract class, some methods can be abstract(i.e. without implementation) while some others can indeed have implementation.Connoisseur
Note that in Java 8, you can now have default methods and static methods in interfaces which means that Java interfaces can have implementation. Reference here. Obviously you referred mainly to .NET, so this is just an observation referring to Java.Schellens
I know this is old, but a very important difference between an interface and an abstract class in C# is that, once you release an interface, changing the interface is a breaking change but not so for an abstract class.Tardy
A very good answer. Perhaps another focus helps: - Interfaces define method skeletons to be implemented by an implementing class and are ideally stateless. - Abstract Classes are a basic Implementation which need to be (partially or fully) overwritten or extended by specific classes - Classes can extend (1) abstract class but may implement several interfaces. In basic terms: Use an Abstract Class if you need to implement common variables and/or methods or skeleton methods. Use an interface only if you want to define a common set of skeleton methods (should ideally not contain variables)Oneiromancy
For Java can I say that - after Java 8 technically the main difference between both is interfaces can't have constructor but abstract classes can?Suez
Nowadays, C# gradually supports implementation with an interface. We just need to think that we can have only one abstract class and many interfaces. Use this to drive our decision. I think we should not try to differentiate them conceptually. Ex: assume that we will have a new language that supports a mix of both, then what? learn.microsoft.com/en-us/dotnet/csharp/language-reference/…Provide
I find this Youtube video very helpful for me to understand the differenceMegalomania
T
947

How about an analogy: when I was in the Air Force, I went to pilot training and became a USAF (US Air Force) pilot. At that point I wasn't qualified to fly anything, and had to attend aircraft type training. Once I qualified, I was a pilot (Abstract class) and a C-141 pilot (concrete class). At one of my assignments, I was given an additional duty: Safety Officer. Now I was still a pilot and a C-141 pilot, but I also performed Safety Officer duties (I implemented ISafetyOfficer, so to speak). A pilot wasn't required to be a safety officer, other people could have done it as well.

All USAF pilots have to follow certain Air Force-wide regulations, and all C-141 (or F-16, or T-38) pilots 'are' USAF pilots. Anyone can be a safety officer. So, to summarize:

  • Pilot: abstract class
  • C-141 Pilot: concrete class
  • ISafety Officer: interface

added note: this was meant to be an analogy to help explain the concept, not a coding recommendation. See the various comments below, the discussion is interesting.

Tumbleweed answered 30/8, 2010 at 4:40 Comment(20)
I really like this analogy, it uses a simple example to explain a slightly complex topicDepose
This is the best way to understand complex OO terminology. In short all theory is worth only when you can make use of it practically. @Tumbleweed you rexample is really easy to grasp then several bullet points (mostly penetrating mind instead of being absorbed!)Elam
Great analogy, small question though. In your example, you (Jay) are a class that inherits from C-141 and implements ISafetyOfficer?Embry
Good point enforge, I think that is correct; in C#, it would be like class Jay : C-141Pilot, ISafetyOfficer { } where Jay inherits from C-141Pilot and implements ISafetyOfficerTumbleweed
I'm still a bit confused. Say, you now got the F-16 and T-38 qualifications, so now class Jay cannot inherit from multiple classes (C-141 pilot, F-16 pilot and T-38 pilot), does that mean that whose classes should become interfaces? ThanksTameratamerlane
In C++ one could use multiple inheritance although many would recommend aggregation over inheritance. https://mcmap.net/q/15832/-inheritance-vs-aggregation-closedTumbleweed
@AlexOkrushko I think you can see it like this: He is still a person, but he added the ability, class, to pilot the C141, and at one point, that got extended by being a ISafetyOfficer for that case. He can still add more functions by adding classes for F16, T38 etc, but he wont inherit it all on top of his person, ie: public class Jay : Person { public C141WithISafetyOfficer iCanPilotC141AndBeISO; } Or something like that?Inessa
Lots of folks have rightly given a +1 to Alex's comment, as it reveals some weakness in this example. First, I would say that Jay would be an instance of C-141Pilot rather than its own class. Additionally, since in the USAF 99% of all pilots are only qualified in one aircraft at a time (FCF and test pilots being notable exceptions) I didn't consider multiple qualifications and how that might be implemented. As I know of a pilot who, 50 years ago, was qualified in 25 different aircraft simultaneously, I think that exemplifies how we do NOT want to use multiple inheritance.Tumbleweed
@Tumbleweed I don't quite follow how your last statement is an argument against multiple inheritance. It seems like that would be an example where multiple inheritance would be useful.Eskill
@Eskill I don't think you would want to have to write new code for every change in qualifications, i.e. class F16pilot, class F15pilot, class F15F16pilot, class C17F16pilot, class C17F15pilot, class C17F15F16pilot, etc. Instead, have class Pilot maintain a list of various qualifications (i.e. List<IQualification> GetQualifications(); )Tumbleweed
Coming in late here.. Jay, regarding @sdasdadas's comment, would it not depend on what a "qualification" entails? If it is only a set of data, a List is fine. But if there is different, actionable logic/behaviour involved with each qualification, would that then imply MI as the solution?Thisbee
Since it is unlikely for one pilot to fly more than one plane at a time, it would be a good opportunity to implement the strategy pattern. A Pilot would have a collection of certifications, and select the correct one at runtime. The certifications would be coded as behaviors that would implement the IFlyPlane interface, with TakeOff, Land, Eject methods.Prepositor
@AlexOkrushko Here's my take. A pilot is-a person. A pilot can-do many things, such as speak (Playable), be drawn (Drawable), etc. And a pilot has many qualifications. An is-a relationship implies a subclass. A can-do relationship implies interfaces. And a has-a relationship implies aggregation - that is, a property of a pilot is his list of qualifications. But real life doesn't always play by our rules.Khosrow
Great analogy! Thanks! I have extra question here: Let's say pilots of any aircraft press the same button on emergency(non-abstract method in Pilot abstract class). This is possible. Why can't we have another emergency button for all Security Officers? (method implementation in interface) Or how do we handle such cases?Dichroscope
@Alex Okrushko: OOP newbie here, in his analogy, should ISafety Officer: interface also be considered a separate class? I noticed he only called the first 2 classes...is that on purpose?Asel
hi TTT, yes that was on purpose, to illustrate some differences between classes and interfaces. As I said, this isn't meant to be a coding recommendation, more an analogy or illustration.Tumbleweed
TTT: having said that, perhaps one implementation could be to have a class like: class SafetyPilot : C141Pilot, ISafetyOfficer { ... } where it exposes the ISafetyOfficer methods, and perhaps is composed of, among other things, a GenericSafetyOfficerImpl object that it uses to perform ISafetyOfficer methodsTumbleweed
This is quite later, but are you saying that basically classes and abstract classes are part of the hierarchy and interfaces are "add-ons" to classes?Bacchae
@Marvin: I think that is a valid way of viewing this. The hierarchy is a chain of is-a relationships (SalariedEmployee is-a Employee is-a Person,where those classes inherit that way). A given subclass of SalariedEmployee may also implement an interface specific to a task, i.e., IBarRaiserInterviewer, where that BarRaiserInterviewer functionality is also included.Tumbleweed
That successfully explained to me nothing at all on abstract class vs inheritance.Darmit
H
807

While your question indicates it's for "general OO", it really seems to be focusing on .NET use of these terms.

In .NET (similar for Java):

  • interfaces can have no state or implementation
  • a class that implements an interface must provide an implementation of all the methods of that interface
  • abstract classes may contain state (data members) and/or implementation (methods)
  • abstract classes can be inherited without implementing the abstract methods (though such a derived class is abstract itself)
  • interfaces may be multiple-inherited, abstract classes may not (this is probably the key concrete reason for interfaces to exist separately from abtract classes - they permit an implementation of multiple inheritance that removes many of the problems of general MI).

As general OO terms, the differences are not necessarily well-defined. For example, there are C++ programmers who may hold similar rigid definitions (interfaces are a strict subset of abstract classes that cannot contain implementation), while some may say that an abstract class with some default implementations is still an interface or that a non-abstract class can still define an interface.

Indeed, there is a C++ idiom called the Non-Virtual Interface (NVI) where the public methods are non-virtual methods that 'thunk' to private virtual methods:

Hyder answered 17/4, 2009 at 17:18 Comment(11)
Thank you. I think since your answer mentions state + a good overview of all rest, i mark your response as a final answer. You are right I asked for general OO, since my first interviewer asked for general OO, but since I am a C# guy, I tend to forget that. ;-) Also thanks for the C++ explanation, as always c++ is mind blowing.Canebrake
I think a key point in the explanation Michael provided is that when implementing an interface you MUST implement all members in the interface, but when inheriting from an abstract class it's NOT REQUIRED by a child class to implement its parent's membersRavens
+1: I'd be willing to bet that those monkeys hosting the interview don't even realise that other languages implement OO differently.Fluorene
@MichaelBurr Michael, in this MSDN article they state that "Abstract methods have no implementation" which conflicts with one of your bullet points. Are there exceptions to their rule or has the rule changed?Desertion
@JL I don't see where the problem lies. You seem to have confused abstract method with abstract class. Abstract methods have no implementation. However, inside of an abstract class, some methods can be abstract(i.e. without implementation) while some others can indeed have implementation.Connoisseur
Note that in Java 8, you can now have default methods and static methods in interfaces which means that Java interfaces can have implementation. Reference here. Obviously you referred mainly to .NET, so this is just an observation referring to Java.Schellens
I know this is old, but a very important difference between an interface and an abstract class in C# is that, once you release an interface, changing the interface is a breaking change but not so for an abstract class.Tardy
A very good answer. Perhaps another focus helps: - Interfaces define method skeletons to be implemented by an implementing class and are ideally stateless. - Abstract Classes are a basic Implementation which need to be (partially or fully) overwritten or extended by specific classes - Classes can extend (1) abstract class but may implement several interfaces. In basic terms: Use an Abstract Class if you need to implement common variables and/or methods or skeleton methods. Use an interface only if you want to define a common set of skeleton methods (should ideally not contain variables)Oneiromancy
For Java can I say that - after Java 8 technically the main difference between both is interfaces can't have constructor but abstract classes can?Suez
Nowadays, C# gradually supports implementation with an interface. We just need to think that we can have only one abstract class and many interfaces. Use this to drive our decision. I think we should not try to differentiate them conceptually. Ex: assume that we will have a new language that supports a mix of both, then what? learn.microsoft.com/en-us/dotnet/csharp/language-reference/…Provide
I find this Youtube video very helpful for me to understand the differenceMegalomania
M
246

I think the answer they are looking for is the fundamental or OPPS philosophical difference.

The abstract class inheritance is used when the derived class shares the core properties and behaviour of the abstract class. The kind of behaviour that actually defines the class.

On the other hand interface inheritance is used when the classes share peripheral behaviour, ones which do not necessarily define the derived class.

For eg. A Car and a Truck share a lot of core properties and behaviour of an Automobile abstract class, but they also share some peripheral behaviour like Generate exhaust which even non automobile classes like Drillers or PowerGenerators share and doesn't necessarily defines a Car or a Truck, so Car, Truck, Driller and PowerGenerator can all share the same interface IExhaust.

Maximilian answered 31/8, 2011 at 12:9 Comment(8)
I think an even better analogy would be "usesFuel" which would show the contract nature of the interface.Meerkat
@Pureferret if accelerate is part of core behaviour of Automobile abstract class, then can't i say accelerate shows the contract nature. what is contract nature? why this word contract introduced whenever we talk about interface?Discrimination
@Discrimination because typically the interface is just where two 'surfaces' meet, but the word contract implies there is an agreement of how the two 'surfaces' meet. It doesn't make sense (at least to me) that generating exhaust is something you 'agree on'. But it makes sense (again to me) that you can agree on needing to useFuel.Meerkat
@Pureferret two surfaces meet? can u give some practical example of significance of contract in software development?Discrimination
@Discrimination I'm sure I could, but I'm not the best qualified here to do so. And a comment is not the best place. Feel free to search the site, and even post a question if you don't find anything in your search.Meerkat
@Pureferret i raised a query at link for the sameDiscrimination
@Pureferret if interface needs to have peripheral behaviour, then why public interface List<E> extends Collection<E> {} is designed to describe core behaviour of list? this is actually contradicting prasun's answer. Both Collection<E> and List<E> are interfaces here.Discrimination
This the best answer, I would also add that multiple interface inheritance has a major advantage. 'run time behavior change' eg: A dog has 4 legs implementation, during runtime a dog can become a Bat (2 legs) but the Bat can also Fly(which wasn't a core functionality till then)! This can never be achieved by an abstract class. So even if you started designing without 'fly' in mind, you are still saved by interfaces.Stagnate
K
236

Short: Abstract classes are used for Modelling a class hierarchy of similar looking classes (For example Animal can be abstract class and Human , Lion, Tiger can be concrete derived classes)

AND

Interface is used for Communication between 2 similar / non similar classes which does not care about type of the class implementing Interface(e.g. Height can be interface property and it can be implemented by Human , Building , Tree. It does not matter if you can eat , you can swim you can die or anything.. it matters only a thing that you need to have Height (implementation in you class) ).

Kordofanian answered 5/4, 2012 at 9:53 Comment(4)
I really like this answer because it is sometimes difficult to answer the "what" is different between things by looking at something more abstract such as intent, instead of only structure (as structurally, an interface and a pure abstract class are pretty much the same thing).Guildhall
It's easy to enumerate what an abstract class vs an interface can do in a specific language but it's more difficult to create an abstraction to give meaning and responsibility to object and what you said totally resume the use of the 2 concept in OO. Thanks!Hypsography
@dhananjay: i see how Height can be seperate from the concept of the Animal class and can be from another different class, but what exactly do you mean by "communication" between the classes? It is simply just defining Height for its own class, correct?Asel
I really like this answer. Doesn't expect me to understand Airforce analogy. Since I am a human, it works well :)Silent
D
79

There are a couple of other differences -

Interfaces can't have any concrete implementations. Abstract base classes can. This allows you to provide concrete implementations there. This can allow an abstract base class to actually provide a more rigorous contract, wheras an interface really only describes how a class is used. (The abstract base class can have non-virtual members defining the behavior, which gives more control to the base class author.)

More than one interface can be implemented on a class. A class can only derive from a single abstract base class. This allows for polymorphic hierarchy using interfaces, but not abstract base classes. This also allows for a pseudo-multi-inheritance using interfaces.

Abstract base classes can be modified in v2+ without breaking the API. Changes to interfaces are breaking changes.

[C#/.NET Specific] Interfaces, unlike abstract base classes, can be applied to value types (structs). Structs cannot inherit from abstract base classes. This allows behavioral contracts/usage guidelines to be applied on value types.

Durning answered 17/4, 2009 at 16:46 Comment(7)
+1 for the key point that more than one interface can be implemented on a class.Micrometry
That's the one real advantage to interfaces over abstract base classes, IMO. Otherwise, I agree with the .NET design guidelines, that now say to "prefer abstract base classes over interfaces"Durning
Although, it would be keen if you could add the point that it's also interfaces can be applied to any class.Micrometry
@altCognito: Figured that was kind of handled with the second paragraph. This did remind me, though, that interfaces work on value types, so I added that.Durning
Thank you very much for this exact description. It is indeed very helpful. I am new here. It is a pity you cant select two responses as "answer". One thing that confuses me is your usage of Abstract 'base' class. All abstract classes are meant to be a base class of a subclass. Why naming the 'base' extra?Canebrake
@Reed, this really confused me "This allows for polymorphic hierarchy using interfaces, but not abstract base classes.", abstract classes allow for polymorphic hierarchy, but here it sounds like your saying they do not, was this a typo or am I reading into this wrong?Berfield
@Gary: That really should probably have been something like "this allows for types to participate in multiple polymorphic hierarchies" - I was trying to say (not particularly well at the time) that interfaces allow you to participate within a polymorphic hierarchy separate from the single base class hierarchy.Durning
A
69

Inheritance
Consider a car and a bus. They are two different vehicles. But still, they share some common properties like they have a steering, brakes, gears, engine etc.
So with the inheritance concept, this can be represented as following ...

public class Vehicle {
    private Driver driver;
    private Seat[] seatArray; //In java and most of the Object Oriented Programming(OOP) languages, square brackets are used to denote arrays(Collections).
    //You can define as many properties as you want here ...
}

Now a Bicycle ...

public class Bicycle extends Vehicle {
    //You define properties which are unique to bicycles here ...
    private Pedal pedal;
}

And a Car ...

public class Car extends Vehicle {
    private Engine engine;
    private Door[] doors;
}

That's all about Inheritance. We use them to classify objects into simpler Base forms and their children as we saw above.

Abstract Classes

Abstract classes are incomplete objects. To understand it further, let's consider the vehicle analogy once again.
A vehicle can be driven. Right? But different vehicles are driven in different ways ... For example, You cannot drive a car just as you drive a Bicycle.
So how to represent the drive function of a vehicle? It is harder to check what type of vehicle it is and drive it with its own function; you would have to change the Driver class again and again when adding a new type of vehicle.
Here comes the role of abstract classes and methods. You can define the drive method as abstract to tell that every inheriting children must implement this function.
So if you modify the vehicle class ...

//......Code of Vehicle Class
abstract public void drive();
//.....Code continues

The Bicycle and Car must also specify how to drive it. Otherwise, the code won't compile and an error is thrown.
In short.. an abstract class is a partially incomplete class with some incomplete functions, which the inheriting children must specify their own.

Interfaces Interfaces are totally incomplete. They do not have any properties. They just indicate that the inheriting children are capable of doing something ...
Suppose you have different types of mobile phones with you. Each of them has different ways to do different functions; Ex: call a person. The maker of the phone specifies how to do it. Here the mobile phones can dial a number - that is, it is dial-able. Let's represent this as an interface.

public interface Dialable {
    public void dial(Number n);
}

Here the maker of the Dialable defines how to dial a number. You just need to give it a number to dial.

// Makers define how exactly dialable work inside.

Dialable PHONE1 = new Dialable() {
    public void dial(Number n) {
        //Do the phone1's own way to dial a number
    }
}

Dialable PHONE2 = new Dialable() {
    public void dial(Number n) {
        //Do the phone2's own way to dial a number
    }
}


//Suppose there is a function written by someone else, which expects a Dialable
......
public static void main(String[] args) {
    Dialable myDialable = SomeLibrary.PHONE1;
    SomeOtherLibrary.doSomethingUsingADialable(myDialable);
}
.....

Hereby using interfaces instead of abstract classes, the writer of the function which uses a Dialable need not worry about its properties. Ex: Does it have a touch-screen or dial pad, Is it a fixed landline phone or mobile phone. You just need to know if it is dialable; does it inherit(or implement) the Dialable interface.

And more importantly, if someday you switch the Dialable with a different one

......
public static void main(String[] args) {
    Dialable myDialable = SomeLibrary.PHONE2; // <-- changed from PHONE1 to PHONE2
    SomeOtherLibrary.doSomethingUsingADialable(myDialable);
}
.....

You can be sure that the code still works perfectly because the function which uses the dialable does not (and cannot) depend on the details other than those specified in the Dialable interface. They both implement a Dialable interface and that's the only thing the function cares about.

Interfaces are commonly used by developers to ensure interoperability(use interchangeably) between objects, as far as they share a common function (just like you may change to a landline or mobile phone, as far as you just need to dial a number). In short, interfaces are a much simpler version of abstract classes, without any properties.
Also, note that you may implement(inherit) as many interfaces as you want but you may only extend(inherit) a single parent class.

More Info Abstract classes vs Interfaces

Anon answered 14/6, 2013 at 13:11 Comment(6)
It is not true that "Interfaces do not have any properties".Paulino
@Bigeyes, java doesn't allow properties in interfaces. I thought it was same in other languages too. Could you please explain more?Anon
I am referring to C#/.Net. Please see the examplePaulino
@Paulino for C# where interfaces can have properties, doesn't that reintroduce the multiple inheritance problem? What happens when a class uses multiple interfaces which have defined the same property? Just curious thanksCatena
@happycoder: re: "Here by using interfaces instead of abstract classes, you need not worry about it's properties. Ex: Does it have a touch-screen or dial pad, Is it a fixed landline phone or mobile phone. You just need to know if it is dialable; does it inherit(or implement) the Dialable interface." - can you show this in a code example, also did not see how it would be inherited...Asel
@happycoder: that helps, especially showing how you can switch between phone1 and 2...thank you.Asel
S
35

These answers are all too long.

  • Interfaces are for defining behaviors.

  • Abstract classes are for defining a thing itself, including its behaviors. That's why we sometimes create an abstract class with some extra properties inheriting an interface.

This also explains why Java only supports single inheritance for classes but puts no restriction on interfaces. Because a concrete object can not be different things, but it can have different behaviors.

Schaumberger answered 8/6, 2019 at 19:0 Comment(1)
Very short and simple. if you can provide a code snippet this would be so perfect.Significs
B
33

The interviewers are barking up an odd tree. For languages like C# and Java, there is a difference, but in other languages like C++ there is not. OO theory doesn't differentiate the two, merely the syntax of language.

An abstract class is a class with both implementation and interface (pure virtual methods) that will be inherited. Interfaces generally do not have any implementation but only pure virtual functions.

In C# or Java an abstract class without any implementation differs from an interface only in the syntax used to inherit from it and the fact you can only inherit from one.

Brause answered 17/4, 2009 at 16:48 Comment(1)
I got asked the same question a week ago, I have no experience with Java but I have been working with C++ for a while now. The interviewer didn't specify languages before asking the question, so I just explained that interfaces in this case were abstract classes with no state or implementations of any kind. I agree that it is an odd question too.Colossians
Q
32

By implementing interfaces you are achieving composition ("has-a" relationships) instead of inheritance ("is-a" relationships). That is an important principle to remember when it comes to things like design patterns where you need to use interfaces to achieve a composition of behaviors instead of an inheritance.

Quandary answered 17/4, 2009 at 16:52 Comment(3)
Interfaces achieve, IMO, more of an "Acts-as-a" relationship. Encapsulation achieves composition better than an interface.Durning
I dont think implementing interfaces would come under composition.Comfortable
Plus, interface more likely use to descript "capability", like IDisposable. It used to share the functionality between classes that these classes "be able to do" something. More example IFlyable can be implemented by bird and plane. But Bird may derive from Class Creature where airecraft derive from AirCraft.Trusty
E
27

Conceptually speaking, keeping the language specific implementation, rules, benefits and achieving any programming goal by using anyone or both, can or cant have code/data/property, blah blah, single or multiple inheritances, all aside

1- Abstract (or pure abstract) Class is meant to implement hierarchy. If your business objects look somewhat structurally similar, representing a parent-child (hierarchy) kind of relationship only then inheritance/Abstract classes will be used. If your business model does not have a hierarchy then inheritance should not be used (here I am not talking about programming logic e.g. some design patterns require inheritance). Conceptually, abstract class is a method to implement hierarchy of a business model in OOP, it has nothing to do with Interfaces, actually comparing Abstract class with Interface is meaningless because both are conceptually totally different things, it is asked in interviews just to check the concepts because it looks both provide somewhat same functionality when implementation is concerned and we programmers usually emphasize more on coding. [Keep this in mind as well that Abstraction is different than Abstract Class].

2- an Interface is a contract, a complete business functionality represented by one or more set of functions. That is why it is implemented and not inherited. A business object (part of a hierarchy or not) can have any number of complete business functionality. It has nothing to do with abstract classes means inheritance in general. For example, a human can RUN, an elephant can RUN, a bird can RUN, and so on, all these objects of different hierarchy would implement the RUN interface or EAT or SPEAK interface. Don't go into implementation as you might implement it as having abstract classes for each type implementing these interfaces. An object of any hierarchy can have a functionality(interface) which has nothing to do with its hierarchy.

I believe, Interfaces were not invented to achieve multiple inheritances or to expose public behavior, and similarly, pure abstract classes are not to overrule interfaces but Interface is a functionality that an object can do (via functions of that interface) and Abstract Class represents a parent of a hierarchy to produce children having core structure (property+functionality) of the parent

When you are asked about the difference, it is actually conceptual difference not the difference in language-specific implementation unless asked explicitly.

I believe, both interviewers were expecting one line straightforward difference between these two and when you failed they tried to drove you towards this difference by implementing ONE as the OTHER

What if you had an Abstract class with only abstract methods?

Epinasty answered 23/1, 2012 at 11:43 Comment(2)
That pretty much sums up the answer to this question quite well.Humo
functionality implemented vs structure extended, nice!Worship
M
26

i will explain Depth Details of interface and Abstract class.if you know overview about interface and abstract class, then first question arrive in your mind when we should use Interface and when we should use Abstract class. So please check below explanation of Interface and Abstract class.

  1. When we should use Interface?

    if you don't know about implementation just we have requirement specification then we go with Interface

  2. When we should use Abstract Class?

    if you know implementation but not completely (partially implementation) then we go with Abstract class.

    Interface

    every method by default public abstract means interface is 100% pure abstract.

    Abstract

    can have Concrete method and Abstract method, what is Concrete method, which have implementation in Abstract class, An abstract class is a class that is declared abstract—it may or may not include abstract methods.

    Interface

    We cannot declared interface as a private, protected

    Q. Why we are not declaring Interface a private and protected?

    Because by default interface method is public abstract so and so that reason that we are not declaring the interface as private and protected.

    Interface method
    also we cannot declared interface as private,protected,final,static,synchronized,native.....

    i will give the reason: why we are not declaring synchronized method because we cannot create object of interface and synchronize are work on object so and son reason that we are not declaring the synchronized method Transient concept are also not applicable because transient work with synchronized.

    Abstract

    we are happily use with public,private final static.... means no restriction are applicable in abstract.

    Interface

    Variables are declared in Interface as a by default public static final so we are also not declared variable as a private, protected.

    Volatile modifier is also not applicable in interface because interface variable is by default public static final and final variable you cannot change the value once it assign the value into variable and once you declared variable into interface you must to assign the variable.

    And volatile variable is keep on changes so it is opp. to final that is reason we are not use volatile variable in interface.

    Abstract

    Abstract variable no need to declared public static final.

i hope this article is useful.

Mathildamathilde answered 31/5, 2014 at 6:33 Comment(2)
I disagree with this point: Abstract class must have at lease one abstract method. It IS possible to have an Abstract class without an Abstract method, as long as you implement it. REFERENCE: An abstract class is a class that is declared abstract—it may or may not include abstract methods. REFERENCE SOURCE: docs.oracle.com/javase/tutorial/java/IandI/abstract.htmlUndermanned
You are talking about technical details and implementation, you are not answering the question in terms of general OOPMargay
O
21

For .Net,

Your answer to The second interviewer is also the answer to the first one... Abstract classes can have implementation, AND state, interfaces cannot...

EDIT: On another note, I wouldn't even use the phrase 'subclass' (or the 'inheritance' phrase) to describe classes that are 'defined to implement' an interface. To me, an interface is a definition of a contract that a class must conform to if it has been defined to 'implement' that interface. It does not inherit anything... You have to add everything yourself, explicitly.

Ortolan answered 17/4, 2009 at 16:48 Comment(4)
Yes! State! Thats what the second interviewer meant with his weird way of saying "public variable" inside an interface. gosh! Abstract Classes can have state, interfaces can't! And yeah the everyone else agrees on the differences between their ways of inheritance as well, which I had forgotten to mention but figured out already later. :) Thanks everyone!Canebrake
More than just state.... Abstract classes can have IMPLEMENTATION. i.e., they can have methods with code in them that actually runs and does something, which gets inhertited and executed by instances of the base classes... Not so with interfacesOrtolan
Even more than that, in one sense, Abstract classes CAN be instantiated, they just have to be instantiated using a derived class definition, not directly. But state variables defined in the abstract class are instantiated in the object created by new-ing up an instance of the derived class. This instance IS an instance of the abstract class as well as being an instance of the derived class - it is after all derived from it. None of this is true for an interface.Ortolan
When you new up an instance of a class defined to implement an interface, it is not an "instance" of that interface, all the syntax does is cause the compiler to examine the code for the class and ensure that every behavior (method, property, event, eventHandler, etc.) which is defined by the interface has been implemented in the code for the class.Ortolan
C
20

Interface : should be used if you want to imply a rule on the components which may or may not be related to each other

Pros:

  1. Allows multiple inheritance
  2. Provides abstraction by not exposing what exact kind of object is being used in the context
  3. provides consistency by a specific signature of the contract

Cons:

  1. Must implement all the contracts defined
  2. Cannot have variables or delegates
  3. Once defined cannot be changed without breaking all the classes

Abstract Class : should be used where you want to have some basic or default behaviour or implementation for components related to each other

Pros:

  1. Faster than interface
  2. Has flexibility in the implementation (you can implement it fully or partially)
  3. Can be easily changed without breaking the derived classes

Cons:

  1. Cannot be instantiated
  2. Does not support multiple inheritance
Choroid answered 14/8, 2014 at 10:27 Comment(2)
Define faster. Is it significant? What does it even mean? opcode for function invocation on an abstract class is faster than opcode for function invocation on an interface?Eightfold
@Eightfold abstract class are slightly faster than interface because of search and call is involved within the interface method. read this coderanch.com/t/503450/java/abstract-class-faster-interfaceChoroid
D
18

I think they didn't like your response because you gave the technical differences instead of design ones. The question is like a troll question for me. In fact, interfaces and abstract classes have a completely different nature so you cannot really compare them. I will give you my vision of what is the role of an interface and what is the role of an abstract class.

interface: is used to ensure a contract and make a low coupling between classes in order to have a more maintainable, scalable and testable application.

abstract class: is only used to factorize some code between classes of the same responsability. Note that this is the main reason why multiple-inheritance is a bad thing in OOP, because a class shouldn't handle many responsabilities (use composition instead).

So interfaces have a real architectural role whereas abstract classes are almost only a detail of implementation (if you use it correctly of course).

Dispermous answered 5/12, 2014 at 10:38 Comment(0)
I
14
  1. Interface:
    • We do not implement (or define) methods, we do that in derived classes.
    • We do not declare member variables in interfaces.
    • Interfaces express the HAS-A relationship. That means they are a mask of objects.
  2. Abstract class:
    • We can declare and define methods in abstract class.
    • We hide constructors of it. That means there is no object created from it directly.
    • Abstract class can hold member variables.
    • Derived classes inherit to abstract class that mean objects from derived classes are not masked, it inherit to abstract class. The relationship in this case is IS-A.

This is my opinion.

Impale answered 23/10, 2011 at 9:0 Comment(0)
E
13
After all that, the interviewer came up with the question "What if you had an 
Abstract class with only abstract methods? How would that be different
from an interface?" 

Docs clearly say that if an abstract class contains only abstract method declarations, it should be declared as an interface instead.

An another interviewer asked me what if you had a Public variable inside
the interface, how would that be different than in Abstract Class?

Variables in Interfaces are by default public static and final. Question could be framed like what if all variables in abstract class are public? Well they can still be non static and non final unlike the variables in interfaces.

Finally I would add one more point to those mentioned above - abstract classes are still classes and fall in a single inheritance tree whereas interfaces can be present in multiple inheritance.

Elephantine answered 20/8, 2013 at 12:34 Comment(0)
C
13

tl;dr; When you see “Is A” relationship use inheritance/abstract class. when you see “has a” relationship create member variables. When you see “relies on external provider” implement (not inherit) an interface.

Interview Question: What is the difference between an interface and an abstract class? And how do you decide when to use what? I mostly get one or all of the below answers: Answer 1: You cannot create an object of abstract class and interfaces.

ZK (That’s my initials): You cannot create an object of either. So this is not a difference. This is a similarity between an interface and an abstract class. Counter Question: Why can’t you create an object of abstract class or interface?

Answer 2: Abstract classes can have a function body as partial/default implementation.

ZK: Counter Question: So if I change it to a pure abstract class, marking all the virtual functions as abstract and provide no default implementation for any virtual function. Would that make abstract classes and interfaces the same? And could they be used interchangeably after that?

Answer 3: Interfaces allow multi-inheritance and abstract classes don’t.

ZK: Counter Question: Do you really inherit from an interface? or do you just implement an interface and, inherit from an abstract class? What’s the difference between implementing and inheriting? These counter questions throw candidates off and make most scratch their heads or just pass to the next question. That makes me think people need help with these basic building blocks of Object-Oriented Programming. The answer to the original question and all the counter questions is found in the English language and the UML. You must know at least below to understand these two constructs better.

Common Noun: A common noun is a name given “in common” to things of the same class or kind. For e.g. fruits, animals, city, car etc.

Proper Noun: A proper noun is the name of an object, place or thing. Apple, Cat, New York, Honda Accord etc.

Car is a Common Noun. And Honda Accord is a Proper Noun, and probably a Composit Proper noun, a proper noun made using two nouns.

Coming to the UML Part. You should be familiar with below relationships:

  • Is A
  • Has A
  • Uses

Let’s consider the below two sentences. - HondaAccord Is A Car? - HondaAccord Has A Car?

Which one sounds correct? Plain English and comprehension. HondaAccord and Cars share an “Is A” relationship. Honda accord doesn’t have a car in it. It “is a” car. Honda Accord “has a” music player in it.

When two entities share the “Is A” relationship it’s a better candidate for inheritance. And Has a relationship is a better candidate for creating member variables. With this established our code looks like this:

abstract class Car
{
   string color;
   int speed;
}
class HondaAccord : Car
{
   MusicPlayer musicPlayer;
}

Now Honda doesn't manufacture music players. Or at least it’s not their main business.

So they reach out to other companies and sign a contract. If you receive power here and the output signal on these two wires it’ll play just fine on these speakers.

This makes Music Player a perfect candidate for an interface. You don’t care who provides support for it as long as the connections work just fine.

You can replace the MusicPlayer of LG with Sony or the other way. And it won’t change a thing in Honda Accord.

Why can’t you create an object of abstract classes?

Because you can’t walk into a showroom and say give me a car. You’ll have to provide a proper noun. What car? Probably a honda accord. And that’s when a sales agent could get you something.

Why can’t you create an object of an interface? Because you can’t walk into a showroom and say give me a contract of music player. It won’t help. Interfaces sit between consumers and providers just to facilitate an agreement. What will you do with a copy of the agreement? It won’t play music.

Why do interfaces allow multiple inheritance?

Interfaces are not inherited. Interfaces are implemented. The interface is a candidate for interaction with the external world. Honda Accord has an interface for refueling. It has interfaces for inflating tires. And the same hose that is used to inflate a football. So the new code will look like below:

abstract class Car
{
    string color;
    int speed;
}
class HondaAccord : Car, IInflateAir, IRefueling
{
    MusicPlayer musicPlayer;
}

And the English will read like this “Honda Accord is a Car that supports inflating tire and refueling”.

Corie answered 3/3, 2020 at 16:26 Comment(0)
E
12

Copied from CLR via C# by Jeffrey Richter...

I often hear the question, “Should I design a base type or an interface?” The answer isn’t always clearcut.

Here are some guidelines that might help you:

■■ IS-A vs. CAN-DO relationship A type can inherit only one implementation. If the derived type can’t claim an IS-A relationship with the base type, don’t use a base type; use an interface. Interfaces imply a CAN-DO relationship. If the CAN-DO functionality appears to belong with various object types, use an interface. For example, a type can convert instances of itself to another type (IConvertible), a type can serialize an instance of itself (ISerializable), etc. Note that value types must be derived from System.ValueType, and therefore, they cannot be derived from an arbitrary base class. In this case, you must use a CAN-DO relationship and define an interface.

■■ Ease of use It’s generally easier for you as a developer to define a new type derived from a base type than to implement all of the methods of an interface. The base type can provide a lot of functionality, so the derived type probably needs only relatively small modifications to its behavior. If you supply an interface, the new type must implement all of the members.

■■ Consistent implementation No matter how well an interface contract is documented, it’s very unlikely that everyone will implement the contract 100 percent correctly. In fact, COM suffers from this very problem, which is why some COM objects work correctly only with Microsoft Word or with Windows Internet Explorer. By providing a base type with a good default implementation, you start off using a type that works and is well tested; you can then modify parts that need modification.

■■ Versioning If you add a method to the base type, the derived type inherits the new method, you start off using a type that works, and the user’s source code doesn’t even have to be recompiled. Adding a new member to an interface forces the inheritor of the interface to change its source code and recompile.

Enlil answered 21/4, 2014 at 19:34 Comment(1)
@AbdullahShoaib is-a and anyone-can-do but not can-do, there is a difference here. this is the basic reason, we need interface. can-do behaviour will be part of abstract class as well.Discrimination
H
11

An interface defines a contract for a service or set of services. They provide polymorphism in a horizontal manner in that two completely unrelated classes can implement the same interface but be used interchangeably as a parameter of the type of interface they implement, as both classes have promised to satisfy the set of services defined by the interface. Interfaces provide no implementation details.

An abstract class defines a base structure for its sublcasses, and optionally partial implementation. Abstract classes provide polymorphism in a vertical, but directional manner, in that any class that inherits the abstract class can be treated as an instance of that abstract class but not the other way around. Abstract classes can and often do contain implementation details, but cannot be instantiated on their own- only their subclasses can be "newed up".

C# does allow for interface inheritance as well, mind you.

Homozygous answered 4/10, 2013 at 21:11 Comment(1)
Using the terms horizontal and vertical made it very clear to imagine the difference.Jed
N
10

Most answers focus on the technical difference between Abstract Class and Interface, but since technically, an interface is basically a kind of abstract class (one without any data or implementation), I think the conceptual difference is far more interesting, and that might be what the interviewers are after.

An Interface is an agreement. It specifies: "this is how we're going to talk to each other". It can't have any implementation because it's not supposed to have any implementation. It's a contract. It's like the .h header files in C.

An Abstract Class is an incomplete implementation. A class may or may not implement an interface, and an abstract class doesn't have to implement it completely. An abstract class without any implementation is kind of useless, but totally legal.

Basically any class, abstract or not, is about what it is, whereas an interface is about how you use it. For example: Animal might be an abstract class implementing some basic metabolic functions, and specifying abstract methods for breathing and locomotion without giving an implementation, because it has no idea whether it should breathe through gills or lungs, and whether it flies, swims, walks or crawls. Mount, on the other hand, might be an Interface, which specifies that you can ride the animal, without knowing what kind of animal it is (or whether it's an animal at all!).

The fact that behind the scenes, an interface is basically an abstract class with only abstract methods, doesn't matter. Conceptually, they fill totally different roles.

Naturism answered 8/4, 2014 at 12:7 Comment(0)
L
9

Interfaces are light weight way to enforce a particular behavior. That is one way to think of.

Loads answered 19/1, 2010 at 5:48 Comment(0)
S
9

As you might have got the theoretical knowledge from the experts, I am not spending much words in repeating all those here, rather let me explain with a simple example where we can use/cannot use Interface and Abstract class.

Consider you are designing an application to list all the features of Cars. In various points you need inheritance in common, as some of the properties like DigitalFuelMeter, Air Conditioning, Seat adjustment, etc are common for all the cars. Likewise, we need inheritance for some classes only as some of the properties like the Braking system (ABS,EBD) are applicable only for some cars.

The below class acts as a base class for all the cars:

public class Cars
{
    public string DigitalFuelMeter()
    {
        return "I have DigitalFuelMeter";
    }

    public string AirCondition()
    {
        return "I have AC";
    }

    public string SeatAdjust()
    {
        return "I can Adjust seat";
    }
}

Consider we have a separate class for each Cars.

public class Alto : Cars
{
    // Have all the features of Car class    
}

public class Verna : Cars
{
    // Have all the features of Car class + Car need to inherit ABS as the Braking technology feature which is not in Cars        
}

public class Cruze : Cars
{
    // Have all the features of Car class + Car need to inherit EBD as the Braking technology feature which is not in Cars        
}

Consider we need a method for inheriting the Braking technology for the cars Verna and Cruze (not applicable for Alto). Though both uses braking technology, the "technology" is different. So we are creating an abstract class in which the method will be declared as Abstract and it should be implemented in its child classes.

public abstract class Brake
{
    public abstract string GetBrakeTechnology();
}

Now we are trying to inherit from this abstract class and the type of braking system is implemented in Verna and Cruze:

public class Verna : Cars,Brake
{
    public override string GetBrakeTechnology()
    {
        return "I use ABS system for braking";
    }       
}

public class Cruze : Cars,Brake
{
    public override string GetBrakeTechnology()
    {
       return "I use EBD system for braking";
    }         
}

See the problem in the above two classes? They inherit from multiple classes which C#.Net doesn't allow even though the method is implemented in the children. Here it comes the need of Interface.

interface IBrakeTechnology
{
    string GetBrakeTechnology();
}

And the implementation is given below:

public class Verna : Cars, IBrakeTechnology
{
    public string GetBrakeTechnology()
    {
        return "I use ABS system for braking";
    }
}

public class Cruze : Cars, IBrakeTechnology
{
   public string GetBrakeTechnology()
   {
       return "I use EBD system for braking";
   }        
}

Now Verna and Cruze can achieve multiple inheritance with its own kind of braking technologies with the help of Interface.

Sutphin answered 13/11, 2014 at 3:7 Comment(2)
This is one of the best explanations because of the examples.Armoire
This makes sense to me without racking the brain. I was just trying to come up with a car example for my students. Thanks for putting in the time to put this together.Fischer
D
7

1) An interface can be seen as a pure Abstract Class, is the same, but despite this, is not the same to implement an interface and inheriting from an abstract class. When you inherit from this pure abstract class you are defining a hierarchy -> inheritance, if you implement the interface you are not, and you can implement as many interfaces as you want, but you can only inherit from one class.

2) You can define a property in an interface, so the class that implements that interface must have that property.

For example:

  public interface IVariable
  {
      string name {get; set;}
  }

The class that implements that interface must have a property like that.

Dumbbell answered 17/4, 2009 at 16:50 Comment(0)
P
7

Though this question is quite old, I would like to add one other point in favor of interfaces:

Interfaces can be injected using any Dependency Injection tools where as Abstract class injection supported by very few.

Purdah answered 25/8, 2012 at 22:22 Comment(1)
I believe you mean that a DI tool can inject a class which implements an interface. Some such tools can also inject classes derived from an abstract class, or are you saying that is impossible?Sanbenito
H
6

From another answer of mine, mostly dealing with when to use one versus the other:

In my experience, interfaces are best used when you have several classes which each need to respond to the same method or methods so that they can be used interchangeably by other code which will be written against those classes' common interface. The best use of an interface is when the protocol is important but the underlying logic may be different for each class. If you would otherwise be duplicating logic, consider abstract classes or standard class inheritance instead.

Humeral answered 17/4, 2009 at 16:48 Comment(0)
W
6

Answer to the second question : public variable defined in interface is static final by default while the public variable in abstract class is an instance variable.

We answered 5/10, 2009 at 12:3 Comment(0)
U
6

Interface Types vs. Abstract Base Classes

Adapted from the Pro C# 5.0 and the .NET 4.5 Framework book.

The interface type might seem very similar to an abstract base class. Recall that when a class is marked as abstract, it may define any number of abstract members to provide a polymorphic interface to all derived types. However, even when a class does define a set of abstract members, it is also free to define any number of constructors, field data, nonabstract members (with implementation), and so on. Interfaces, on the other hand, contain only abstract member definitions. The polymorphic interface established by an abstract parent class suffers from one major limitation in that only derived types support the members defined by the abstract parent. However, in larger software systems, it is very common to develop multiple class hierarchies that have no common parent beyond System.Object. Given that abstract members in an abstract base class apply only to derived types, we have no way to configure types in different hierarchies to support the same polymorphic interface. By way of example, assume you have defined the following abstract class:

public abstract class CloneableType
{
// Only derived types can support this
// "polymorphic interface." Classes in other
// hierarchies have no access to this abstract
// member.
   public abstract object Clone();
}

Given this definition, only members that extend CloneableType are able to support the Clone() method. If you create a new set of classes that do not extend this base class, you can’t gain this polymorphic interface. Also, you might recall that C# does not support multiple inheritance for classes. Therefore, if you wanted to create a MiniVan that is-a Car and is-a CloneableType, you are unable to do so:

// Nope! Multiple inheritance is not possible in C#
// for classes.
public class MiniVan : Car, CloneableType
{
}

As you would guess, interface types come to the rescue. After an interface has been defined, it can be implemented by any class or structure, in any hierarchy, within any namespace or any assembly (written in any .NET programming language). As you can see, interfaces are highly polymorphic. Consider the standard .NET interface named ICloneable, defined in the System namespace. This interface defines a single method named Clone():

public interface ICloneable
{
object Clone();
}
Uncommon answered 29/8, 2014 at 23:29 Comment(0)
C
5

From Coding Perspective

An Interface can replace an Abstract Class if the Abstract Class has only abstract methods. Otherwise changing Abstract class to interface means that you will be losing out on code re-usability which Inheritance provides.

From Design Perspective

Keep it as an Abstract Class if it's an "Is a" relationship and you need a subset or all of the functionality. Keep it as Interface if it's a "Should Do" relationship.

Decide what you need: just the policy enforcement, or code re-usability AND policy.

Cimino answered 21/2, 2014 at 1:25 Comment(0)
E
5

For sure it is important to understand the behavior of interface and abstract class in OOP (and how languages handle them), but I think it is also important to understand what exactly each term means. Can you imagine the if command not working exactly as the meaning of the term? Also, actually some languages are reducing, even more, the differences between an interface and an abstract... if by chance one day the two terms operate almost identically, at least you can define yourself where (and why) should any of them be used for.

If you read through some dictionaries and other fonts you may find different meanings for the same term but having some common definitions. I think these two meanings I found in this site are really, really good and suitable.

Interface:

A thing or circumstance that enables separate and sometimes incompatible elements to coordinate effectively.

Abstract:

Something that concentrates in itself the essential qualities of anything more extensive or more general, or of several things; essence.

Example:

You bought a car and it needs fuel.

enter image description here

Your car model is XYZ, which is of genre ABC, so it is a concrete car, a specific instance of a car. A car is not a real object. In fact, it is an abstract set of standards (qualities) to create a specific object. In short, Car is an abstract class, it is "something that concentrates in itself the essential qualities of anything more extensive or more general".

The only fuel that matches the car manual specification should be used to fill up the car tank. In reality, there is nothing to restrict you to put any fuel but the engine will work properly only with the specified fuel, so it is better to follow its requirements. The requirements say that it accepts, as other cars of the same genre ABC, a standard set of fuel.

In an Object Oriented view, fuel for genre ABC should not be declared as a class because there is no concrete fuel for a specific genre of car out there. Although your car could accept an abstract class Fuel or VehicularFuel, you must remember that your only some of the existing vehicular fuel meet the specification, those that implement the requirements in your car manual. In short, they should implement the interface ABCGenreFuel, which "... enables separate and sometimes incompatible elements to coordinate effectively".

Addendum

In addition, I think you should keep in mind the meaning of the term class, which is (from the same site previously mentioned):

Class:

A number of persons or things regarded as forming a group by reason of common attributes, characteristics, qualities, or traits; kind;

This way, a class (or abstract class) should not represent only common attributes (like an interface), but some kind of group with common attributes. An interface doesn't need to represent a kind. It must represent common attributes. This way, I think classes and abstract classes may be used to represent things that should not change its aspects often, like a human being a Mammal, because it represents some kinds. Kinds should not change themselves that often.

Evannia answered 5/1, 2016 at 4:29 Comment(1)
too much fluff, don't make it sound more confusing to people than it already may be.Orleanist
B
3

Couple of other differences:

Abstract classes can have static methods, properties, fields etc. and operators, interfaces can't. Cast operator allows casting to/from abstract class but don't allow casting to/from interface.

So pretty much you can use abstract class on its own even if it is never implemented (through its static members) and you can't use interface on its own in any way.

Bureaucratic answered 12/5, 2010 at 22:10 Comment(3)
in Java, interface can have member variable but by default they become public static ..so interface can have static fieldsSecund
Yes interface can have static fields. BUT interface cannot have static methods.Wine
https://mcmap.net/q/15871/-interface-vs-abstract-class-general-ooBiweekly
M
3

Interface:- == contract.Whichever class implements it has to follow all the specification of interface.

A real-time example would be any ISO marked Product.ISO gives set of rules/specification on how the product should be build and what minimum set of features it Must have.

This is nothing but subset of properties product Must have.ISO will sign the product only if it satisfies the its standards.

Now take a look at this code

public interface IClock{       //defines a minimum set of specification which a clock should have

    public abstract Date getTime();
    public abstract int getDate();
}
public class Fasttrack: Clock {
    // Must have getTime() and getTime() as it implements IClock
    // It also can have other set of feature like 
    public void startBackgroundLight() {
        // watch with internal light in it.
    }
    .... //Fastrack can support other feature as well
    ....
    ....
}

Here a Fastrack is called as watch because it has all that features that a watch must suppost(Minimum set of features).

Why and When Abstract:

From MSDN:

The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class. Abstract simply means if you cannot define it completely declare it as an abstract .Implementing class will complete this implementation.

E.g -: Suppose I declare a Class Recipe as abstract but I dont know which recipe to be made.Then I will generalize this class to define the common definition of any recipe.The implantation of recipe will depend on implementing dish.

Abstract class can consist of abstract methods as well as not abstract method So you can notice the difference in Interface.So not necessarily every method your implementing class must have.You only need to override the abstract methods.

In Simple words If you want tight coupling use Interface o/w use in case of lose coupling Abstract Class

Malinowski answered 12/9, 2013 at 15:22 Comment(0)
G
1

Except for comparing Abstract class with Interface, it is meaningful to compare Abstract class with Concrete class.

Use abstract class as you use concrete classes just except the times you don't want/aren't able to instantiate them without being extended. And make the methods that you don't want/aren't able to implement abstract methods.

If you like analogy, think chromium as an abstract class (you can't use it as a browser so it cannot be instantiated), chrome and opera as concrete classes derived from chromium and browser add-on structure as interface.

Goles answered 7/4, 2017 at 13:25 Comment(0)
N
0

Abstract class deals with efficiently packaging the class functionality whereas interface is for intention/contract/communication and is supposed to be shared with other classes/modules.

Using abstract classes as both contract and (partial) contract implementer violates SRP. Using abstract class as a contract (dependency) puts restriction on creating multiple abstract classes for better re-usability.

In the sample below, using abstract class as a contract to OrderManager would create issues as we have two different ways of processing the orders - based on customer type and category (Customer can be either direct or indirect or gold or silver). Hence interface is used for contract and abstract class is used for different workflow enforcement

public interface IOrderProcessor
{
    bool Process(string orderNumber);
}

public abstract class CustomerTypeOrderProcessor: IOrderProcessor
{
    public bool Process(string orderNumber) => IsValid(orderNumber) ? ProcessOrder(orderNumber) : false;

    protected abstract bool ProcessOrder(string orderNumber);

    protected abstract bool IsValid(string orderNumber);
}

public class DirectCustomerOrderProcessor : CustomerTypeOrderProcessor
{
    protected override bool IsValid(string orderNumber) => string.IsNullOrEmpty(orderNumber); 

    protected override bool ProcessOrder(string orderNumber) => true; 
}

public class InDirectCustomerOrderProcessor : CustomerTypeOrderProcessor
{
    protected override bool IsValid(string orderNumber) => orderNumber.StartsWith("EX");

    protected override bool ProcessOrder(string orderNumber) => true;
}

public abstract class CustomerCategoryOrderProcessor : IOrderProcessor
{
    public bool Process(string orderNumber) => ProcessOrder(GetDiscountPercentile(orderNumber), orderNumber);

    protected abstract int GetDiscountPercentile(string orderNumber);

    protected abstract bool ProcessOrder(int discount, string orderNumber);
}

public class GoldCustomer : CustomerCategoryOrderProcessor
{
    protected override int GetDiscountPercentile(string orderNumber) => 15;

    protected override bool ProcessOrder(int discount, string orderNumber) => true;

}

public class SilverCustomer : CustomerCategoryOrderProcessor
{
    protected override int GetDiscountPercentile(string orderNumber) => 10;

    protected override bool ProcessOrder(int discount, string orderNumber) => true;

}

public class OrderManager
{
    private readonly IOrderProcessor _orderProcessor;// Not CustomerTypeOrderProcessor or CustomerCategoryOrderProcessor 

    //Using abstract class here would create problem as we have two different abstract classes
    public OrderManager(IOrderProcessor orderProcessor) => _orderProcessor = orderProcessor;
}
Nazler answered 7/5, 2018 at 6:26 Comment(0)
B
0

Abstract classes are not pure abstraction because its collection of concrete(implemented methods) as well as unimplemented methods. But Interfaces are pure abstraction because there are only unimplemented methods not concrete methods.

One more difference is

An abstract class allows you to create functionality that subclasses can implement or override. An interface only allows you to define functionality, not implement it.

When to use Abstract classes

  1. If user want write common functionality for all objects.
  2. Abstract classes are best choice for reimplementation in future that to add more functionality without affecting of end user.

When to use Interfaces

  1. If user want to write different functionality that would be different functionality on objects.
  2. Interfaces are best choice that if not need to modify the requirements once interface has been published.
Biweekly answered 13/12, 2022 at 7:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.