将光标移到/点击文章中的句子上,可以查看译文。      显示繁体中文内容    显示简体中文内容

Interface vs Abstract Class (general OO)
接口VS 抽象类Class ( 常规OO )

I have had recently 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 a 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.Abstract class can also have class variables beside Events, Delegates, Properties and Methods.A class can only implement one abstract class only due 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. An another interviewer asked me what if you had a Public variable inside the interface, how would that be different than in 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 :

时间:

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 :

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.

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.

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) ).

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.

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 {
 public Driver driver;
 public 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..
 public Pedal pedal;
}

And a Car..


public class Car extends Vehicle {
 public Engine engine;
 public 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 is capable of doing something..
Suppose you have different types of mobile phones with you.each of them have 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.


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

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

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.
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 much simpler version of abstract classes, without any properties.
Also note that that you may implement(inherit) as many interfaces as you want but you may only extend(inherit) a single parent class.

more InfoAbstract classes vs Interfaces

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.

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.

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.

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 inheritance, all aside

1- Abstract (or pure abstract) Class is a mean 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- Interface is a contract, a complete business functionality represented by one of 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.Dont 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 inheritance or to expose public behavior, and similarly, pure abstract classes are not to over rule 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 straight forward 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?

...