Related
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#.
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?
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:
When to use an interface instead of an abstract class and vice versa
Interfaces vs. Abstract Classes
How do you decide between using an Abstract Class and an Interface?
What is the difference between an interface and abstract class?
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.
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:
http://www.gotw.ca/publications/mill18.htm
http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface
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 {
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
If you consider java as OOP language to answer this question, Java 8 release causes some of the content in above answers as obsolete. Now java interface can have default methods with concrete implementation.
Oracle website provides key differences between interface and abstract class.
Consider using abstract classes if :
You want to share code among several closely related classes.
You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
You want to declare non-static or non-final fields.
Consider using interfaces if :
You expect that unrelated classes would implement your interface. For example,many unrelated objects can implement Serializable interface.
You want to specify the behaviour of a particular data type, but not concerned about who implements its behaviour.
You want to take advantage of multiple inheritance of type.
In simple terms, I would like to use
interface: To implement a contract by multiple unrelated objects
abstract class: To implement the same or different behaviour among multiple related objects
Have a look at code example to understand things in clear way : How should I have explained the difference between an Interface and an Abstract class?
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.
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.
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?
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.
When we should use Interface?
if you don't know about implementation just we have requirement specification then we go with Interface
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.
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.
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:
Allows multiple inheritance
Provides abstraction by not exposing what exact kind of object is being used in the context
provides consistency by a specific signature of the contract
Cons:
Must implement all the contracts defined
Cannot have variables or delegates
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:
Faster than interface
Has flexibility in the implementation (you can implement it fully or partially)
Can be easily changed without breaking the derived classes
Cons:
Cannot be instantiated
Does not support multiple inheritance
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).
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.
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.
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.
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.
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”.
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.
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.
Interfaces are light weight way to enforce a particular behavior. That is one way to think of.
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.
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.
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.
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.
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();
}
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.
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.
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.
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.
I have decided to start doing small coding projects on my own that focus on code quality instead of code quantity and have a question about the use of abstract classes.
Now I know the differences between abstract classes and interfaces with the biggest one (I think) being that interface allow you to only define methods that need to be implemented by classes using the interface and abstract classes allowing you to define both method and members along with default method implementation if you so desire. My question is what the the main benefit of use an abstract class vs a normal class? The only real difference between the two that I can think of is that you can not create an instance of an abstract class. Are there any other differences between the two?
Strictly from a design perspective, it is best to simplify things. I believe the best way to simplify things is to use a simple analogy. Let's use an analogy of birds...
Interface: use this when you want to enforce certain functions which need to be defined. e.g. IBird has a contract for ScreamLikeABird and Fly (interface functions). But you can get more specific and have an IOstrich that has a Run contract. You may also have an IHawk that has an Attack contract...etc.
Abstract: use this when you want to enforce base functions and have base properties. e.g. Avian could be a base class for birds which may have a function called LayEgg as well as propeties called Age, Species, NumberOfChicks...etc. These things don't/shouldn't change the behavior of a bird, since all birds lay eggs...etc. But not all birds sounds the same when it scream or flies the same way (some dont even fly)....etc.... hence they should be implemented via an interface(s).
In addition to not being able to create instances of abstract classes, some languages may support having abstract methods in abstract classes - similar to interfaces, an abstract method will have to be implemented by the class inheriting from the abstract class.
The main benefit of abstract classes in my opinion is if there is some code that has to be shared between classes of the same type. Usually you could use an interface for this, but sometimes the functionality of such classes may overlap and you would end up with code duplication. In this case you can use an abstract class and just put the code there.
In OO world, abstract classes used to impose some design & implementation constraints. Nothing more. You never have to use abstract classes in any case. But there might be cases that you better impose those constraints. So what are them? Let's look at by comparing it's oo-counterparts.
Abstract classes vs interfaces
As you know, these are two of the primary concepts of inheritance.
Basically, interface is used just to declare that you're willing to inherit the underlying service and that's it. Contains no implementation & has no functionality. In that sense, interface is abstract. That's why it's a more a design constraint than an implementation constraint. Think of a headphone jack on a speaker. Each headphone needs to implement the jack interface (with start, stop, listen, turnDown, turnUp methods). Each headphone should override this interface to inherit the functionality that the speaker provides and implement accordingly.
Abstract classes, on the other hand, may include methods with an implementation. That's the basic difference and in that sense it may utilize reusing more than an interface. Moreover, they may contain private, protected & non-static fields which you can't via interfaces. You may force subclasses to implement some must-have functionalities with abstract methods (those without implementations). Abstract classes more agile than interfaces.
Of course not to mention, you may only extend one class in java in where you may implement number of interfaces.
Abstract classes vs regular classes
So why not to use regular classes then. What's the benefit of using abstract class? This is pretty simple. If you use abstract classes, you force the core functionality to be implemented by the children. As a developer, you don't need to remember that you should implement the essential functions. This is where abstract classes imposing design constraints over regular classes. Plus by making the class abstract you avoid that (incomplete) class to be created accidentally.
The only reason for declaring a class as abstract is so that it can't be instantiated. There are situations where you will have common functionality that is shared between a number of classes, but by itself that common functionality does not represent an object or represents an incomplete object. In that case, you define the common functionality as abstract so that it can't be instantiated.
in my opinion abstract classes have more use in real projects as on books. some times project managers just provide the methods declaration and you have to write code for the methods without modify the core syntax provided by manager. so that is how an abstract class is use full. in simple class method define,declared and coded in same time but not in abstract classes.
for ex:-
abstract class Test
{
abstract void show();//method provided
}
class Child extends Test
{
void show()//coding
{
System.out.println("saurav");
}
}
class main
{
public static void main(String[] args)
{
Test c = new Child();
c.show();
}
}
Abstract Classes vs Regular Classes vs Interface.
Abstract class usually supports an idea of the generalisation and to contribute from programmers to keep a quite little brain disipline by designing multi-years projects because of they when include an abstract methods have to describe an implementation that abstract methods in subling classes, however, this feature is a disadvantage for a short-time projects when a developer have a zeitnot.
In automotive manufacturing terms, an Interface is a spec sheet for a "car" which says it has four wheels, five seats, an engine, etc, while an Abstract Class is a partially assembled car in a crate that you have to finish off to your own requirements. E.g. Subaru uses the same exact chassis for the Impreza, Forester and XV/Crosstrek. So the chassis is the "abstract class" which has common features and functions but isn't a "car" yet. The body and interior MUST be added after the fact before you can say you've built a car. The engine is also common among all three, though you can choose to swap it out for a turbocharged version IF you wish.
This might help you,
Lets consider traveler who may use any type of vehicle i.e car,cycle,bike etc...
but all vehicles moves in the same way with different speed constraints so we can have one
abstract class Avehicle
{
string fuel;
public void move()
{
sysout("moving");
}
}
but all vehicles breaking system is different
interface Ivehicle
{
public void breakorstop();
}
class Traveler
{
Ivehicle v;
//Settrers and getters
public drive()
{
v.move();
}
public break()
{
v.breakorstop();
}
}
So finally
Car or Cycle or Bike classes can extend Avehicle and can Implement Vehicle interface
Abstract classes can be used to store methods in an OOP-based "library"; since the class doesn't need to be instantiated, and would make little sense for it to be, keeping common static methods inside of an abstract class is a common practice.
I've been reading a lot about interfaces and class inheritance in Java, and I know how to do both and I think I have a good feel for both. But it seems that nobody ever really compares the two side by side and explains when and why you would want to use one or the other. I have not found a lot of times when implementing an interface would be a better system than extending a superclass.
So when do you implement an interface and when do you extend a superclass?
Use an interface if you want to define a contract. I.e. X must take Y and return Z. It doesn't care how the code is doing that. A class can implement multiple interfaces.
Use an abstract class if you want to define default behaviour in non-abstract methods so that the endusers can reuse it without rewriting it again and again. A class can extend from only one other class. An abstract class with only abstract methods can be as good definied as an interface. An abstract class without any abstract method is recognizeable as the Template Method pattern (see this answer for some real world examples).
An abstract class in turn can perfectly implement an interface whenever you want to provide the enduser freedom in defining the default behaviour.
You should choose an interface if all you want is to define a contract i.e. method signatures that you want the inheriting classes to implement. An interface can have no implementation at all. The inheriting classes are free to choose their own implementation.
Sometimes you want to define partial implementation in a base type and want to leave the rest to inheriting classes. If that is the case, choose an abstract class. An abstract class can define method implementations and variables while leaving some methods as abstract. Extending classes can choose how to implement the abstract methods while they also have the partial implementation provided by the superclass.
One extreme of abstract classes is a pure abstract class - one that has only abstract methods and nothing else. If it comes to pure abstract class vs. an interface, go with the interface. Java allows only single implementation inheritance whereas it allows multiple interface inheritance meaning that a class can implement multiple interfaces but can extend only one class. So choosing a pure abstract class over the interface will mean that the subclass will not be allowed to extend any other class while implementing the abstract methods.
Use an interface to define behavior. User (abstract) classes (and subclasses) to provide implementation. They are not mutually exclusive; they can all work together.
For example, lets say you are defining a data access object. You want your DAO to be able to load data. So put a load method on the interface. This means that anything that wants to call itself a DAO must implement load. Now lets say you need to load A and B. You can create a generic abstract class that is parameterized (generics) to provide the outline on how the load works. You then subclass that abstract class to provide the concrete implementations for A and B.
The main reason for using abstract classes and interfaces are different.
An abstract class should be used when you have classes that have identical implementations for a bunch of methods, but vary in a few.
This may be a bad example, but the most obvious use of abstract classes in the Java framework is within the java.io classes. OutputStream is just a stream of bytes. Where that stream goes to depends entirely on which subclass of OutputStream you're using... FileOutputStream, PipedOutputStream, the output stream created from a java.net.Socket's getOutputStream method...
Note: java.io also uses the Decorator pattern to wrap streams in other streams/readers/writers.
An interface should be used when you just want to guarantee that a class implements a set of methods, but you don't care how.
The most obvious use of interfaces is within the Collections framework.
I don't care how a List adds/removes elements, so long as I can call add(something) and get(0) to put and get elements. It may use an array (ArrayList, CopyOnWriteArrayList), linked list (LinkedList), etc...
The other advantage in using interfaces is that a class may implement more than one. LinkedList is an implementation of both List and Deque.
No one?
http://mindprod.com/jgloss/interfacevsabstract.html
EDIT: I should supply more than a link
Here's a situation. To build on the car example below, consider this
interface Drivable {
void drive(float miles);
}
abstract class Car implements Drivable {
float gallonsOfGas;
float odometer;
final float mpg;
protected Car(float mpg) { gallonsOfGas = 0; odometer = 0; this.mpg = mpg; }
public void addGas(float gallons) { gallonsOfGas += gallons; }
public void drive(float miles) {
if(miles/mpg > gallonsOfGas) throw new NotEnoughGasException();
gallonsOfGas -= miles/mpg;
odometer += miles;
}
}
class LeakyCar extends Car { // still implements Drivable because of Car
public addGas(float gallons) { super.addGas(gallons * .8); } // leaky tank
}
class ElectricCar extends Car {
float electricMiles;
public void drive(float miles) { // can we drive the whole way electric?
if(electricMiles > miles) {
electricMiles -= miles;
odometer += miles;
return; // early return here
}
if(electricMiles > 0) { // exhaust electric miles first
if((miles-electricMiles)/mpg > gallonsOfGas)
throw new NotEnoughGasException();
miles -= electricMiles;
odometer += electricMiles;
electricMiles = 0;
}
// finish driving
super.drive(miles);
}
}
I think that interfaces work best when you use them to express that the object has a certain property or behavior, that spans multiple inheritance trees, and is only clearly defined for each class.
For example think of Comparable. If you wanted to create a class Comparable to be extended by other classes, it would have to be very high on the inheritance tree, possible right after Object, and the property it expresses is that two objects of that type can be compared, but there's no way to define that generally (you can't have an implementation of compareTo directly in the Comparable class, it's different for every class that implements it).
Classes work best when they define something clear, you know what properties and behaviors they have, and have actual implementations for methods, that you want to pass down to the children.
So classes work when you need to define a concrete object like a human, or a car, and interfaces work better when you need more abstract behavior that's too general to belong to any inheritance tree, like the ability to be compared (Comparable) or to be run (Runnable).
One method of choosing between an interface and a base class is the consideration of code ownership. If you control all the code then a base class is a viable option. If on the other hand many different companies might want to produce replaceable components, that is define a contract then an interface is your only choice.
I found some articles, particularly some who describe why you should not use implementation inheritance (i.e. superclasses):
Why extends is evil
Inheritance of implementation is evil
Implementation inheritance
Implementation inheritance
Java inheritance FAQ
I guess I'll give the classic car example.
When you have a car interface, you can create a Ford, a Chevy, and an Oldsmobile. In other words, you create different kinds of cars from a car interface.
When you have a car class, you can then extend the car class to make a truck, or a bus. In other words, you add new attributes to the sub classes while keeping the attributes of the base or super class.
You can think of extending from a super class if the derived class is of the same type.I mean that when a class extends an abstract class, they both should be of the same type, the only difference being that the super class has a more general behavior and the sub class has a more specific behavior. An interface is a totally different concept. When a class implements an interface, its either to expose some API(contract) or to get certain behavior. To give an example, I would say that Car is an abstract class. You can extend many classes from it like say Ford, Chevy and so on which are each of type car. But then if you need certain specific behavior like say you need a GPS in a car then the concrete class, eg Ford should implement GPS interface.
If you only want to inherit method signatures (name, arguments, return type) in the subclasses, use an interface, but if you also want to inherit implementation code, use a superclass.
What exactly is the difference between an interface and an abstract class?
Interfaces
An interface is a contract: The person writing the interface says, "hey, I accept things looking that way", and the person using the interface says "OK, the class I write looks that way".
An interface is an empty shell. There are only the signatures of the methods, which implies that the methods do not have a body. The interface can't do anything. It's just a pattern.
For example (pseudo code):
// I say all motor vehicles should look like this:
interface MotorVehicle
{
void run();
int getFuel();
}
// My team mate complies and writes vehicle looking that way
class Car implements MotorVehicle
{
int fuel;
void run()
{
print("Wrroooooooom");
}
int getFuel()
{
return this.fuel;
}
}
Implementing an interface consumes very little CPU, because it's not a class, just a bunch of names, and therefore there isn't any expensive look-up to do. It's great when it matters, such as in embedded devices.
Abstract classes
Abstract classes, unlike interfaces, are classes. They are more expensive to use, because there is a look-up to do when you inherit from them.
Abstract classes look a lot like interfaces, but they have something more: You can define a behavior for them. It's more about a person saying, "these classes should look like that, and they have that in common, so fill in the blanks!".
For example:
// I say all motor vehicles should look like this:
abstract class MotorVehicle
{
int fuel;
// They ALL have fuel, so lets implement this for everybody.
int getFuel()
{
return this.fuel;
}
// That can be very different, force them to provide their
// own implementation.
abstract void run();
}
// My teammate complies and writes vehicle looking that way
class Car extends MotorVehicle
{
void run()
{
print("Wrroooooooom");
}
}
Implementation
While abstract classes and interfaces are supposed to be different concepts, the implementations make that statement sometimes untrue. Sometimes, they are not even what you think they are.
In Java, this rule is strongly enforced, while in PHP, interfaces are abstract classes with no method declared.
In Python, abstract classes are more a programming trick you can get from the ABC module and is actually using metaclasses, and therefore classes. And interfaces are more related to duck typing in this language and it's a mix between conventions and special methods that call descriptors (the __method__ methods).
As usual with programming, there is theory, practice, and practice in another language :-)
The key technical differences between an abstract class and an interface are:
Abstract classes can have constants, members, method stubs (methods without a body) and defined methods, whereas interfaces can only have constants and methods stubs.
Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public (they are defined public by default).
When inheriting an abstract class, a concrete child class must define the abstract methods, whereas an abstract class can extend another abstract class and abstract methods from the parent class don't have to be defined.
Similarly, an interface extending another interface is not responsible for implementing methods from the parent interface. This is because interfaces cannot define any implementation.
A child class can only extend a single class (abstract or concrete), whereas an interface can extend or a class can implement multiple other interfaces.
A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility (public).
An Interface contains only the definition / signature of functionality, and if we have some common functionality as well as common signatures, then we need to use an abstract class. By using an abstract class, we can provide behavior as well as functionality both in the same time. Another developer inheriting abstract class can use this functionality easily, as they would only need to fill in the blanks.
Taken from:
http://www.dotnetbull.com/2011/11/difference-between-abstract-class-and.html
http://www.dotnetbull.com/2011/11/what-is-abstract-class-in-c-net.html
http://www.dotnetbull.com/2011/11/what-is-interface-in-c-net.html
An explanation can be found here: http://www.developer.com/lang/php/article.php/3604111/PHP-5-OOP-Interfaces-Abstract-Classes-and-the-Adapter-Pattern.htm
An abstract class is a class that is
only partially implemented by the
programmer. It may contain one or more
abstract methods. An abstract method
is simply a function definition that
serves to tell the programmer that the
method must be implemented in a child
class.
An interface is similar to an abstract
class; indeed interfaces occupy the
same namespace as classes and abstract
classes. For that reason, you cannot
define an interface with the same name
as a class. An interface is a fully
abstract class; none of its methods
are implemented and instead of a class
sub-classing from it, it is said to
implement that interface.
Anyway I find this explanation of interfaces somewhat confusing. A more common definition is: An interface defines a contract that implementing classes must fulfill. An interface definition consists of signatures of public members, without any implementing code.
I don't want to highlight the differences, which have been already said in many answers ( regarding public static final modifiers for variables in interface & support for protected, private methods in abstract classes)
In simple terms, I would like to say:
interface: To implement a contract by multiple unrelated objects
abstract class: To implement the same or different behaviour among multiple related objects
From the Oracle documentation
Consider using abstract classes if :
You want to share code among several closely related classes.
You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
You want to declare non-static or non-final fields.
Consider using interfaces if :
You expect that unrelated classes would implement your interface. For example,many unrelated objects can implement Serializable interface.
You want to specify the behaviour of a particular data type, but not concerned about who implements its behaviour.
You want to take advantage of multiple inheritance of type.
abstract class establishes "is a" relation with concrete classes. interface provides "has a" capability for classes.
If you are looking for Java as programming language, here are a few more updates:
Java 8 has reduced the gap between interface and abstract classes to some extent by providing a default method feature. An interface does not have an implementation for a method is no longer valid now.
Refer to this documentation page for more details.
Have a look at this SE question for code examples to understand better.
How should I have explained the difference between an Interface and an Abstract class?
Some important differences:
In the form of a table:
As stated by Joe from javapapers:
1.Main difference is methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can
have instance methods that implements a default behavior.
2.Variables declared in a Java interface is by default final. An abstract class may contain non-final variables.
3.Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private,
protected, etc..
4.Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”.
5.An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java
interfaces.
6.A Java class can implement multiple interfaces but it can extend only one abstract class.
7.Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a
main() exists.
8.In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.
The main point is that:
Abstract is object oriented. It offers the basic data an 'object' should have and/or functions it should be able to do. It is concerned with the object's basic characteristics: what it has and what it can do. Hence objects which inherit from the same abstract class share the basic characteristics (generalization).
Interface is functionality oriented. It defines functionalities an object should have. Regardless what object it is, as long as it can do these functionalities, which are defined in the interface, it's fine. It ignores everything else. An object/class can contain several (groups of) functionalities; hence it is possible for a class to implement multiple interfaces.
When you want to provide polymorphic behaviour in an inheritance hierarchy, use abstract classes.
When you want polymorphic behaviour for classes which are completely unrelated, use an interface.
I am constructing a building of 300 floors
The building's blueprint interface
For example, Servlet(I)
Building constructed up to 200 floors - partially completed---abstract
Partial implementation, for example, generic and HTTP servlet
Building construction completed-concrete
Full implementation, for example, own servlet
Interface
We don't know anything about implementation, just requirements. We can
go for an interface.
Every method is public and abstract by default
It is a 100% pure abstract class
If we declare public we cannot declare private and protected
If we declare abstract we cannot declare final, static, synchronized, strictfp and native
Every interface has public, static and final
Serialization and transient is not applicable, because we can't create an instance for in interface
Non-volatile because it is final
Every variable is static
When we declare a variable inside an interface we need to initialize variables while declaring
Instance and static block not allowed
Abstract
Partial implementation
It has an abstract method. An addition, it uses concrete
No restriction for abstract class method modifiers
No restriction for abstract class variable modifiers
We cannot declare other modifiers except abstract
No restriction to initialize variables
Taken from DurgaJobs Website
Let's work on this question again:
The first thing to let you know is that 1/1 and 1*1 results in the same, but it does not mean that multiplication and division are same. Obviously, they hold some good relationship, but mind you both are different.
I will point out main differences, and the rest have already been explained:
Abstract classes are useful for modeling a class hierarchy. At first glance of any requirement, we are partially clear on what exactly is to be built, but we know what to build. And so your abstract classes are your base classes.
Interfaces are useful for letting other hierarchy or classes to know that what I am capable of doing. And when you say I am capable of something, you must have that capacity. Interfaces will mark it as compulsory for a class to implement the same functionalities.
If you have some common methods that can be used by multiple classes go for abstract classes.
Else if you want the classes to follow some definite blueprint go for interfaces.
Following examples demonstrate this.
Abstract class in Java:
abstract class Animals
{
// They all love to eat. So let's implement them for everybody
void eat()
{
System.out.println("Eating...");
}
// The make different sounds. They will provide their own implementation.
abstract void sound();
}
class Dog extends Animals
{
void sound()
{
System.out.println("Woof Woof");
}
}
class Cat extends Animals
{
void sound()
{
System.out.println("Meoww");
}
}
Following is an implementation of interface in Java:
interface Shape
{
void display();
double area();
}
class Rectangle implements Shape
{
int length, width;
Rectangle(int length, int width)
{
this.length = length;
this.width = width;
}
#Override
public void display()
{
System.out.println("****\n* *\n* *\n****");
}
#Override
public double area()
{
return (double)(length*width);
}
}
class Circle implements Shape
{
double pi = 3.14;
int radius;
Circle(int radius)
{
this.radius = radius;
}
#Override
public void display()
{
System.out.println("O"); // :P
}
#Override
public double area()
{
return (double)((pi*radius*radius)/2);
}
}
Some Important Key points in a nutshell:
The variables declared in Java interface are by default final. Abstract classes can have non-final variables.
The variables declared in Java interface are by default static. Abstract classes can have non-static variables.
Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..
It's pretty simple actually.
You can think of an interface as a class which is only allowed to have abstract methods and nothing else.
So an interface can only "declare" and not define the behavior you want the class to have.
An abstract class allows you to do both declare (using abstract methods) as well as define (using full method implementations) the behavior you want the class to have.
And a regular class only allows you to define, not declare, the behavior/actions you want the class to have.
One last thing,
In Java, you can implement multiple interfaces, but you can only extend one (Abstract Class or Class)...
This means inheritance of defined behavior is restricted to only allow one per class... ie if you wanted a class that encapsulated behavior from Classes A,B&C you would need to do the following: Class A extends B, Class C extends A .. its a bit of a round about way to have multiple inheritance...
Interfaces on the other hand, you could simply do: interface C implements A, B
So in effect Java supports multiple inheritance only in "declared behavior" ie interfaces, and only single inheritance with defined behavior.. unless you do the round about way I described...
Hopefully that makes sense.
The comparison of interface vs. abstract class is wrong. There should be two other comparisons instead: 1) interface vs. class and 2) abstract vs. final class.
Interface vs Class
Interface is a contract between two objects. E.g., I'm a Postman and you're a Package to deliver. I expect you to know your delivery address. When someone gives me a Package, it has to know its delivery address:
interface Package {
String address();
}
Class is a group of objects that obey the contract. E.g., I'm a box from "Box" group and I obey the contract required by the Postman. At the same time I obey other contracts:
class Box implements Package, Property {
#Override
String address() {
return "5th Street, New York, NY";
}
#Override
Human owner() {
// this method is part of another contract
}
}
Abstract vs Final
Abstract class is a group of incomplete objects. They can't be used, because they miss some parts. E.g., I'm an abstract GPS-aware box - I know how to check my position on the map:
abstract class GpsBox implements Package {
#Override
public abstract String address();
protected Coordinates whereAmI() {
// connect to GPS and return my current position
}
}
This class, if inherited/extended by another class, can be very useful. But by itself - it is useless, since it can't have objects. Abstract classes can be building elements of final classes.
Final class is a group of complete objects, which can be used, but can't be modified. They know exactly how to work and what to do. E.g., I'm a Box that always goes to the address specified during its construction:
final class DirectBox implements Package {
private final String to;
public DirectBox(String addr) {
this.to = addr;
}
#Override
public String address() {
return this.to;
}
}
In most languages, like Java or C++, it is possible to have just a class, neither abstract nor final. Such a class can be inherited and can be instantiated. I don't think this is strictly in line with object-oriented paradigm, though.
Again, comparing interfaces with abstract classes is not correct.
The only difference is that one can participate in multiple inheritance and other cannot.
The definition of an interface has changed over time. Do you think an interface just has method declarations only and are just contracts? What about static final variables and what about default definitions after Java 8?
Interfaces were introduced to Java because of the diamond problem with multiple inheritance and that's what they actually intend to do.
Interfaces are the constructs that were created to get away with the multiple inheritance problem and can have abstract methods, default definitions and static final variables.
See Why does Java allow static final variables in interfaces when they are only intended to be contracts?.
Interface: Turn ( Turn Left, Turn Right.)
Abstract Class: Wheel.
Class: Steering Wheel, derives from Wheel, exposes Interface Turn
One is for categorizing behavior that can be offered across a diverse range of things, the other is for modelling an ontology of things.
In short the differences are the following:
Syntactical Differences Between Interface and Abstract Class:
Methods and members of an abstract class can have any visibility. All methods of an interface must be public. //Does not hold true from Java 9 anymore
A concrete child class of an Abstract Class must define all the abstract methods. An Abstract child class can have abstract methods. An interface extending another interface need not provide default implementation for methods inherited from the parent interface.
A child class can only extend a single class. An interface can extend multiple interfaces. A class can implement multiple interfaces.
A child class can define abstract methods with the same or less restrictive visibility, whereas class implementing an interface must define all interface methods as public.
Abstract Classes can have constructors but not interfaces.
Interfaces from Java 9 have private static methods.
In Interfaces now:
public static - supported
public abstract - supported
public default - supported
private static - supported
private abstract - compile error
private default - compile error
private - supported
Many junior developers make the mistake of thinking of interfaces, abstract and concrete classes as slight variations of the same thing, and choose one of them purely on technical grounds: Do I need multiple inheritance? Do I need some place to put common methods? Do I need to bother with something other than just a concrete class? This is wrong, and hidden in these questions is the main problem: "I". When you write code for yourself, by yourself, you rarely think of other present or future developers working on or with your code.
Interfaces and abstract classes, although apparently similar from a technical point of view, have completely different meanings and purposes.
Summary
An interface defines a contract that some implementation will fulfill for you.
An abstract class provides a default behavior that your implementation can reuse.
Alternative summary
An interface is for defining public APIs
An abstract class is for internal use, and for defining SPIs
On the importance of hiding implementation details
A concrete class does the actual work, in a very specific way. For example, an ArrayList uses a contiguous area of memory to store a list of objects in a compact manner which offers fast random access, iteration, and in-place changes, but is terrible at insertions, deletions, and occasionally even additions; meanwhile, a LinkedList uses double-linked nodes to store a list of objects, which instead offers fast iteration, in-place changes, and insertion/deletion/addition, but is terrible at random access. These two types of lists are optimized for different use cases, and it matters a lot how you're going to use them. When you're trying to squeeze performance out of a list that you're heavily interacting with, and when picking the type of list is up to you, you should carefully pick which one you're instantiating.
On the other hand, high level users of a list don't really care how it is actually implemented, and they should be insulated from these details. Let's imagine that Java didn't expose the List interface, but only had a concrete List class that's actually what LinkedList is right now. All Java developers would have tailored their code to fit the implementation details: avoid random access, add a cache to speed up access, or just reimplement ArrayList on their own, although it would be incompatible with all the other code that actually works with List only. That would be terrible... But now imagine that the Java masters actually realize that a linked list is terrible for most actual use cases, and decided to switch over to an array list for their only List class available. This would affect the performance of every Java program in the world, and people wouldn't be happy about it. And the main culprit is that implementation details were available, and the developers assumed that those details are a permanent contract that they can rely on. This is why it's important to hide implementation details, and only define an abstract contract. This is the purpose of an interface: define what kind of input a method accepts, and what kind of output is expected, without exposing all the guts that would tempt programmers to tweak their code to fit the internal details that might change with any future update.
An abstract class is in the middle between interfaces and concrete classes. It is supposed to help implementations share common or boring code. For example, AbstractCollection provides basic implementations for isEmpty based on size is 0, contains as iterate and compare, addAll as repeated add, and so on. This lets implementations focus on the crucial parts that differentiate between them: how to actually store and retrieve data.
APIs versus SPIs
Interfaces are low-cohesion gateways between different parts of code. They allow libraries to exist and evolve without breaking every library user when something changes internally. It's called Application Programming Interface, not Application Programming Classes. On a smaller scale, they also allow multiple developers to collaborate successfully on large scale projects, by separating different modules through well documented interfaces.
Abstract classes are high-cohesion helpers to be used when implementing an interface, assuming some level of implementation details. Alternatively, abstract classes are used for defining SPIs, Service Provider Interfaces.
The difference between an API and an SPI is subtle, but important: for an API, the focus is on who uses it, and for an SPI the focus is on who implements it.
Adding methods to an API is easy, all existing users of the API will still compile. Adding methods to an SPI is hard, since every service provider (concrete implementation) will have to implement the new methods. If interfaces are used to define an SPI, a provider will have to release a new version whenever the SPI contract changes. If abstract classes are used instead, new methods could either be defined in terms of existing abstract methods, or as empty throw not implemented exception stubs, which will at least allow an older version of a service implementation to still compile and run.
A note on Java 8 and default methods
Although Java 8 introduced default methods for interfaces, which makes the line between interfaces and abstract classes even blurrier, this wasn't so that implementations can reuse code, but to make it easier to change interfaces that serve both as an API and as an SPI (or are wrongly used for defining SPIs instead of abstract classes).
Which one to use?
Is the thing supposed to be publicly used by other parts of the code, or by other external code? Add an interface to it to hide the implementation details from the public abstract contract, which is the general behavior of the thing.
Is the thing something that's supposed to have multiple implementations with a lot of code in common? Make both an interface and an abstract, incomplete implementation.
Is there ever going to be only one implementation, and nobody else will use it? Just make it a concrete class.
"ever" is long time, you could play it safe and still add an interface on top of it.
A corollary: the other way around is often wrongly done: when using a thing, always try to use the most generic class/interface that you actually need. In other words, don't declare your variables as ArrayList theList = new ArrayList(), unless you actually have a very strong dependency on it being an array list, and no other type of list would cut it for you. Use List theList = new ArrayList instead, or even Collection theCollection = new ArrayList if the fact that it's a list, and not any other type of collection doesn't actually matter.
Not really the answer to the original question, but once you have the answer to the difference between them, you will enter the when-to-use-each dilemma:
When to use interfaces or abstract classes? When to use both?
I've limited knowledge of OOP, but seeing interfaces as an equivalent of an adjective in grammar has worked for me until now (correct me if this method is bogus!). For example, interface names are like attributes or capabilities you can give to a class, and a class can have many of them: ISerializable, ICountable, IList, ICacheable, IHappy, ...
You can find clear difference between interface and abstract class.
Interface
Interface only contains abstract methods.
Force users to implement all methods when implements the interface.
Contains only final and static variables.
Declare using interface keyword.
All methods of an interface must be defined as public.
An interface can extend or a class can implement multiple other
interfaces.
Abstract class
Abstract class contains abstract and non-abstract methods.
Does not force users to implement all methods when inherited the
abstract class.
Contains all kinds of variables including primitive and non-primitive
Declare using abstract keyword.
Methods and members of an abstract class can be defined with any
visibility.
A child class can only extend a single class (abstract or concrete).
I am 10 yrs late to the party but would like to attempt any way. Wrote a post about the same on medium few days back. Thought of posting it here.
tl;dr; When you see “Is A” relationship use inheritance/abstract class. when you see “has a” relationship create member variables. When you see “relies on external provider” implement (not inherit) an interface.
Interview Question: What is the difference between an interface and an abstract class? And how do you decide when to use what?
I mostly get one or all of the below answers:
Answer 1: You cannot create an object of abstract class and interfaces.
ZK (That’s my initials): You cannot create an object of either. So this is not a difference. This is a similarity between an interface and an abstract class. Counter
Question: Why can’t you create an object of abstract class or interface?
Answer 2: Abstract classes can have a function body as partial/default implementation.
ZK: Counter Question: So if I change it to a pure abstract class, marking all the virtual functions as abstract and provide no default implementation for any virtual function. Would that make abstract classes and interfaces the same? And could they be used interchangeably after that?
Answer 3: Interfaces allow multi-inheritance and abstract classes don’t.
ZK: Counter Question: Do you really inherit from an interface? or do you just implement an interface and, inherit from an abstract class? What’s the difference between implementing and inheriting?
These counter questions throw candidates off and make most scratch their heads or just pass to the next question. That makes me think people need help with these basic building blocks of Object-Oriented Programming.
The answer to the original question and all the counter questions is found in the English language and the UML.
You must know at least below to understand these two constructs better.
Common Noun: A common noun is a name given “in common” to things of the same class or kind. For e.g. fruits, animals, city, car etc.
Proper Noun: A proper noun is the name of an object, place or thing. Apple, Cat, New York, Honda Accord etc.
Car is a Common Noun. And Honda Accord is a Proper Noun, and probably a Composit Proper noun, a proper noun made using two nouns.
Coming to the UML Part. You should be familiar with below relationships:
Is A
Has A
Uses
Let’s consider the below two sentences.
- HondaAccord Is A Car?
- HondaAccord Has A Car?
Which one sounds correct? Plain English and comprehension. HondaAccord and Cars share an “Is A” relationship. Honda accord doesn’t have a car in it. It “is a” car. Honda Accord “has a” music player in it.
When two entities share the “Is A” relationship it’s a better candidate for inheritance. And Has a relationship is a better candidate for creating member variables.
With this established our code looks like this:
abstract class Car
{
string color;
int speed;
}
class HondaAccord : Car
{
MusicPlayer musicPlayer;
}
Now Honda doesn't manufacture music players. Or at least it’s not their main business.
So they reach out to other companies and sign a contract. If you receive power here and the output signal on these two wires it’ll play just fine on these speakers.
This makes Music Player a perfect candidate for an interface. You don’t care who provides support for it as long as the connections work just fine.
You can replace the MusicPlayer of LG with Sony or the other way. And it won’t change a thing in Honda Accord.
Why can’t you create an object of abstract classes?
Because you can’t walk into a showroom and say give me a car. You’ll have to provide a proper noun. What car? Probably a honda accord. And that’s when a sales agent could get you something.
Why can’t you create an object of an interface?
Because you can’t walk into a showroom and say give me a contract of music player. It won’t help. Interfaces sit between consumers and providers just to facilitate an agreement. What will you do with a copy of the agreement? It won’t play music.
Why do interfaces allow multiple inheritance?
Interfaces are not inherited. Interfaces are implemented.
The interface is a candidate for interaction with the external world.
Honda Accord has an interface for refueling. It has interfaces for inflating tires. And the same hose that is used to inflate a football. So the new code will look like below:
abstract class Car
{
string color;
int speed;
}
class HondaAccord : Car, IInflateAir, IRefueling
{
MusicPlayer musicPlayer;
}
And the English will read like this “Honda Accord is a Car that supports inflating tire and refueling”.
Key Points:
Abstract class can have property, Data fields ,Methods (complete /
incomplete) both.
If method or Properties define in abstract keyword that must override in derived class.(its work as a tightly coupled
functionality)
If define abstract keyword for method or properties in abstract class you can not define body of method and get/set value for
properties and that must override in derived class.
Abstract class does not support multiple inheritance.
Abstract class contains Constructors.
An abstract class can contain access modifiers for the subs, functions, properties.
Only Complete Member of abstract class can be Static.
An interface can inherit from another interface only and cannot inherit from an abstract class, where as an abstract class can inherit from another abstract class or another interface.
Advantage:
It is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.
If various implementations are of the same kind and use common behavior or status then abstract class is better to use.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Its allow fast execution than interface.(interface Requires more time to find the actual method in the corresponding classes.)
It can use for tight and loosely coupling.
find details here...
http://pradeepatkari.wordpress.com/2014/11/20/interface-and-abstract-class-in-c-oops/
The shortest way to sum it up is that an interface is:
Fully abstract, apart from default and static methods; while it has definitions (method signatures + implementations) for default and static methods, it only has declarations (method signatures) for other methods.
Subject to laxer rules than classes (a class can implement multiple interfaces, and an interface can inherit from multiple interfaces). All variables are implicitly constant, whether specified as public static final or not. All members are implicitly public, whether specified as such or not.
Generally used as a guarantee that the implementing class will have the specified features and/or be compatible with any other class which implements the same interface.
Meanwhile, an abstract class is:
Anywhere from fully abstract to fully implemented, with a tendency to have one or more abstract methods. Can contain both declarations and definitions, with declarations marked as abstract.
A full-fledged class, and subject to the rules that govern other classes (can only inherit from one class), on the condition that it cannot be instantiated (because there's no guarantee that it's fully implemented). Can have non-constant member variables. Can implement member access control, restricting members as protected, private, or private package (unspecified).
Generally used either to provide as much of the implementation as can be shared by multiple subclasses, or to provide as much of the implementation as the programmer is able to supply.
Or, if we want to boil it all down to a single sentence: An interface is what the implementing class has, but an abstract class is what the subclass is.
Inheritance is used for two purposes:
To allow an object to regard parent-type data members and method implementations as its own.
To allow a reference to an objects of one type to be used by code which expects a reference to supertype object.
In languages/frameworks which support generalized multiple inheritance, there is often little need to classify a type as either being an "interface" or an "abstract class". Popular languages and frameworks, however, will allow a type to regard one other type's data members or method implementations as its own even though they allow a type to be substitutable for an arbitrary number of other types.
Abstract classes may have data members and method implementations, but can only be inherited by classes which don't inherit from any other classes. Interfaces put almost no restrictions on the types which implement them, but cannot include any data members or method implementations.
There are times when it's useful for types to be substitutable for many different things; there are other times when it's useful for objects to regard parent-type data members and method implementations as their own. Making a distinction between interfaces and abstract classes allows each of those abilities to be used in cases where it is most relevant.
Differences between abstract class and interface on behalf of real implementation.
Interface: It is a keyword and it is used to define the template or blue print of an object and it forces all the sub classes would follow the same prototype,as for as implementation, all the sub classes are free to implement the functionality as per it's requirement.
Some of other use cases where we should use interface.
Communication between two external objects(Third party integration in our application) done through Interface here Interface works as Contract.
Abstract Class: Abstract,it is a keyword and when we use this keyword before any class then it becomes abstract class.It is mainly used when we need to define the template as well as some default functionality of an object that is followed by all the sub classes and this way it removes the redundant code and one more use cases where we can use abstract class, such as we want no other classes can directly instantiate an object of the class, only derived classes can use the functionality.
Example of Abstract Class:
public abstract class DesireCar
{
//It is an abstract method that defines the prototype.
public abstract void Color();
// It is a default implementation of a Wheel method as all the desire cars have the same no. of wheels.
// and hence no need to define this in all the sub classes in this way it saves the code duplicasy
public void Wheel() {
Console.WriteLine("Car has four wheel");
}
}
**Here is the sub classes:**
public class DesireCar1 : DesireCar
{
public override void Color()
{
Console.WriteLine("This is a red color Desire car");
}
}
public class DesireCar2 : DesireCar
{
public override void Color()
{
Console.WriteLine("This is a red white Desire car");
}
}
Example Of Interface:
public interface IShape
{
// Defines the prototype(template)
void Draw();
}
// All the sub classes follow the same template but implementation can be different.
public class Circle : IShape
{
public void Draw()
{
Console.WriteLine("This is a Circle");
}
}
public class Rectangle : IShape
{
public void Draw()
{
Console.WriteLine("This is a Rectangle");
}
}
I'd like to add one more difference which makes sense.
For example, you have a framework with thousands of lines of code. Now if you want to add a new feature throughout the code using a method enhanceUI(), then it's better to add that method in abstract class rather in interface. Because, if you add this method in an interface then you should implement it in all the implemented class but it's not the case if you add the method in abstract class.
To give a simple but clear answer, it helps to set the context : you use both when you do not want to provide full implementations.
The main difference then is an interface has no implementation at all (only methods without a body) while abstract classes can have members and methods with a body as well, i.e. can be partially implemented.
usually Abstract class used for core of something but interface used for appending peripheral.
when you want to create base type for vehicle you should use abstract class but if you want to add some functionality or property that is not part of base concept of vehicle you should use interface,for example you want to add "ToJSON()" function.
interface has wide range of abstraction rather than abstract class.
you can see this in passing arguments.look this example:
if you use vehicle as argument you just can use one of its derived type (bus or car-same category-just vehicle category).
but when you use IMoveable interface as argument you have more choices.
The topic of abstract classes vs interfaces is mostly about semantics.
Abstract classes act in different programming languages often as a superset of interfaces, except one thing and that is, that you can implement multiple interfaces, but inherit only one class.
An interface defines what something must be able to do; like a contract, but does not provide an implementation of it.
An abstract class defines what something is and it commonly hosts shared code between the subclasses.
For example a Formatter should be able to format() something. The common semantics to describe something like that would be to create an interface IFormatter with a declaration of format() that acts like a contract. But IFormatter does not describe what something is, but just what it should be able to to. The common semantics to describe what something actually is, is to create a class. In this case we create an abstract class... So we create an abstract class Formatter which implements the interface. That is a very descriptive code, because we now know we have a Formatter and we now know what every Formatter must be able to do.
Also one very important topic is documentation (at least for some people...). In your documentation you probably want to explain within your subclasses what a Formatter actually is. It is very convenient to have an abstract class Formatter to which documentation you can link to within your subclasses. That is very convenient and generic. On the other hand if you do not have an abstract class Formatter and only an interface IFormatter you would have to explain in each of your subclasses what a Formatter actucally is, because an interface is a contract and you would not describe what a Formatter actually is within the documentation of an interface — at least it would be not something common to do and you would break the semantics that most developers consider to be correct.
Note: It is a very common pattern to make an abstract class implement an interface.
An abstract class is a class whose object cannot be created or a class which cannot be instantiated.
An abstract method makes a class abstract.
An abstract class needs to be inherited in order to override the methods that are declared in the abstract class.
No restriction on access specifiers.
An abstract class can have constructor and other concrete(non abstarct methods ) methods in them but interface cannot have.
An interface is a blueprint/template of methods.(eg. A house on a paper is given(interface house) and different architects will use their ideas to build it(the classes of architects implementing the house interface) .
It is a collection of abstract methods , default methods , static methods , final variables and nested classes.
All members will be either final or public , protected and private access specifiers are not allowed.No object creation is allowed.
A class has to be made in order to use the implementing interface and also to override the abstract method declared in the interface. An interface is a good example of loose coupling(dynamic polymorphism/dynamic binding)
An interface implements polymorphism and abstraction.It tells what to do but how to do is defined by the implementing class.
For Eg. There's a car company and it wants that some features to be same for all the car it is manufacturing so for that the company would be making an interface vehicle which will have those features and different classes of car(like Maruti Suzkhi , Maruti 800) will override those features(functions).
Why interface when we already have abstract class?
Java supports only multilevel and hierarchal inheritance but with the help of interface we can implement multiple inheritance.
In an interface all methods must be only definitions, not single one should be implemented.
But in an abstract class there must an abstract method with only definition, but other methods can be also in the abstract class with implementation...
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#.
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?
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:
When to use an interface instead of an abstract class and vice versa
Interfaces vs. Abstract Classes
How do you decide between using an Abstract Class and an Interface?
What is the difference between an interface and abstract class?
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.
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:
http://www.gotw.ca/publications/mill18.htm
http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface
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 {
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
If you consider java as OOP language to answer this question, Java 8 release causes some of the content in above answers as obsolete. Now java interface can have default methods with concrete implementation.
Oracle website provides key differences between interface and abstract class.
Consider using abstract classes if :
You want to share code among several closely related classes.
You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
You want to declare non-static or non-final fields.
Consider using interfaces if :
You expect that unrelated classes would implement your interface. For example,many unrelated objects can implement Serializable interface.
You want to specify the behaviour of a particular data type, but not concerned about who implements its behaviour.
You want to take advantage of multiple inheritance of type.
In simple terms, I would like to use
interface: To implement a contract by multiple unrelated objects
abstract class: To implement the same or different behaviour among multiple related objects
Have a look at code example to understand things in clear way : How should I have explained the difference between an Interface and an Abstract class?
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.
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.
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?
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.
When we should use Interface?
if you don't know about implementation just we have requirement specification then we go with Interface
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.
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.
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:
Allows multiple inheritance
Provides abstraction by not exposing what exact kind of object is being used in the context
provides consistency by a specific signature of the contract
Cons:
Must implement all the contracts defined
Cannot have variables or delegates
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:
Faster than interface
Has flexibility in the implementation (you can implement it fully or partially)
Can be easily changed without breaking the derived classes
Cons:
Cannot be instantiated
Does not support multiple inheritance
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).
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.
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.
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.
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.
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”.
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.
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.
Interfaces are light weight way to enforce a particular behavior. That is one way to think of.
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.
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.
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.
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.
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();
}
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.
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.
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.
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.