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 following problem:
I am creating an aplication for creating UML diagrams. Right now just to simplify everything I assume only couple of available diagram elements:
class
interface
generalization
interface implementation
association
aggregation
I decided to create one common abstract class for all of that elements:
abstract DiagramElement which has 2 subclasses also abstract:
DiagramRelation
DiagramObject
Nextly DiagramRelation has 4 subclasses:
Generalization
InterfaceImplementation
Assosication
Aggregation
And DiagramObject has 2 subclasses:
Interface
Class
I really wanted to post a picture so it would be all much more simplier but I don't have enough reputation points so sorry.
I came across following problem: each of this element have a different visual representation, ie: interface has only methods etc so each of this element will need to be show differently - I don't want to use multiple "if" instructions for it.
I use WPF and I decided that every control will place it's contest into StackPanel which will be placed inside MyContextControl (inherits after ContextControl and add interface atribute):
public interface IDiagramElementDraw
{
public StackPanel Draw();
}
public MyContextControl : ContextControl
{
private IDiagramElementDraw _drawingInterface;
private StackPanel context;
public DrawControl()
{
context = _drawingInterface.Draw();
}
}
But I don't know which class should implement IDiagramElementDraw interface - I don't want to implement it at the level of Interface, Class, Generalization etc classes because I want them to only represent logical information about each element.
I would appreciate any help, feel free to post complete different solution - this one may be completely wrong, this was just my idea.
From my answer to another question:
Distinction between using an interface or an abstract class as a
basis: An abstract class ia a shared implementation; an interface is a
shared contract. They share some commonality, but meet different
requirements. For instance, you might want to share requirements (a
common interface IProjectile) between small arms and heavier weapons,
or between lethal and non-lethal weapons, while implementing the three
categories on three distinct abstract classes (LethalSmallArms,
NonLethalSmallArms, and Howitzers) that all implement the common
interface IProjectile.
From another answer of mine
An abstract class can, with care, be extended in a non-breaking
manner; all changes to an interface are breaking changes.
Update: In contrast, an interface can be an in or out type-parameter
and an abstract class cannot. Sometimes one or the other is more
appropriate for a given design, and sometimes it is a toss-up.
Generally speaking, both interfaces and abstract classes are useful; it just depends on WHO:
Interfaces are more desirable for someone to USE your API, for they
gurantee him with absolute freedom.
Abstract classes are more
desirable for someone to EXTEND your API, for they ease the task of
extending.
The more sensitive option is to combine both: Desing a hierarchy of public interfaces (for using), and provide also abstract classes with the members mostly common to any implementation (for extending), and if you want to let the client extend your API, make them public.
And, in the bottom of all the hierarchy, private implementation classes are expected.
Using polymorphism could be a good solution and will prevent "if" conditions.
1. You could have an IDrawable interface that will have a Draw method on it.
This interface will be implemented by you abstract class.
2. Then you will have an ElementDrawing and its derived classes which will draw the different types (classes, interfaces,...). It could be a virtual property that will be instantiated in each DiagramElement differently according to the type.
class abstract DiagramElement : IDrawable
{
public abstract void Draw();
}
class ClassDiagramElement:DiagramElement
{
public overrides void Draw()
{
ElementDrawing elementDrawing = new ClassDrawing();
elementDrawing.DrawElement();
}
}
class InterfaceDiagramElement:DiagramElement
{
public overrides void Draw()
{
ElementDrawing elementDrawing = new InterfaceDrawing();
elementDrawing.DrawElement([maybe need some parameters]);
}
}
ElementDrawing is a base class for all the derived classes that draw the different elements in your UML. It can be defined as virtual property as mentioned above.
From my experience I think the following is true. If I am missing a major point please let me know.
Interface:
Every single Method declared in an Interface will have to be implemented in the subclass. Only Events, Delegates, Properties (C#) and Methods can exist in a Interface. A class can implement multiple Interfaces.
Abstract Class:
Only Abstract methods have to be implemented by the subclass. An Abstract class can have normal methods with implementations. Abstract class can also have class variables beside Events, Delegates, Properties and Methods. A class can only implement one abstract class only due non-existence of Multi-inheritance in C#.
So even that difference doesn't explain the question
1) What if you had an Abstract class with only abstract methods? How would that be different from an interface?
2) What if you had a Public variable inside the interface, how would that be different than in Abstract Class?
So any explanation will be vary help full.
Besides the technical differences it is mainly the intension of your design that should lead you to the decision to use one or the other:
Interfaces define the public API of the classes implementing them. Your goal of using an interface should be to show the usage of the classes that implement it. It is no side effect but a central design goal that a class can implement different interfaces to show the different roles it can act in.
An abstract class should implement some basic algorithm or common behaviour. It is mainly to join the common functionality of the subclasses in one place. Its purpose is to define the internal usage or flow and not the public interface. If you want to publish the usage of an abstract class it should implement a separate interface.
So:
1) An abstract class with only public abstract methods does not make any sense when you use the guidelines above. An abstract class can define protected abstract methods to define a flow or algorithm. But that is not possible with an interface.
2) Aditionally to the public properties abstract classes can define protected instance variables and therefor have many more usage scenarios (see explanation above).
EDIT: The "java" tag was removed by the author. I tried to make this as general as possible and it should be true for both java and C#
In Java:
An abstract class can implement an interface.
An interface cannot extend an abstract class.
BTW: Strangely - an abstract class can implement and interface without actually doing so.
interface I {
public String hello ();
}
interface J {
public String goodbye ();
}
abstract class A implements I, J {
#Override
abstract public String hello ();
}
class B extends A {
#Override
public String hello() {
return "Hello";
}
#Override
public String goodbye() {
return "goodbye";
}
}
All the variables of an Interface are by default public and static, you can not have a only public variable in an interface, whereas in an Abstract class you can declare a public variable.
If a class extends an Abstract class there is no any contract between them. Class which extends it may or may not override the abstract methods, however in case of interface there is a strict contract between the interface and the class that implements it, i.e the class will have to override all the method of that interface. So from the abstract method point of view they appears to be same, but are having completely different properties and advantages.
While your question indicates it's for "general OO", it really seems to be focusing on .NET use of these terms.
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 itslef)
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
What if you had an Abstract class with only abstract methods? How
would that be different from an interface?
You can implement multiple interfaces but extend only one class
Abstract class are more immune to changes then interface becuase if you change an interface it would break the class implementing it.
Interface can have only static final fields..Abstract class can have any type of fields.
interface don't have constructor but abstract class can have it
But java docs say this
If an abstract class contains only abstract method declarations, it
should be declared as an interface instead.
Even if all the methods in today's version of an abstract class are abstract, future version of the class could add virtual or non-virtual methods without forcing modifications to implementations nor recompilation of consumers. By contrast, adding any member to an interface will generally require all classes which implement the interface be modified to implement that member, and both implementations and consumers will generally have to be recompiled regardless of whether the change added anything that wasn't already implemented.
The fact that abstract changes may be changed without breaking implementations or consumers is a big advantage in favor of abstract classes. On the other hand, an abstract class will force any implementing class to derive from it alone and no other class. By contrast, an interface will pose almost restrictions on what its implementers are allowed to inherit or derive from. That is a big advantage in favor of interfaces.
Because abstract classes and interfaces each have definite advantages, there are times when either may be better than the other. Conceptually, it would be possible to add a couple features to the way interfaces work that would give them the advantages presently enjoyed only by abstract classes, but I know of no particular plans to do so.
Your class can extends only one abstract class and implements many interfaces.
Well, in an abstract class you could also have fields, and auto-properties wouldn't need to be reimplemented. You can also specify access specifiers that aren't public. Also, it has better scalability (e.g. you can use [Obsolete] to mark an old implementation, and then make the new one call the old one by default). Also, it would stop you from having any more inheritance of classes. Another thing is that you can set static fields in abstract classes.
Also, interfaces are usually something that performs an action, while classes are about being that.
*1) What if you had an Abstract class with only abstract methods? How would that be different from an interface?*
By default the methods in an interface are 'public abstract' and the abstract class will also have the abstract methods as 'public abstract'.
If the abstract class contains only abstracts methods then it's better to make it an interface.
*2) What if you had a Public variable inside the interface, how would that be different than in Abstract Class?*
Interfaces can't have variables. If you meant properties, events, delegates etc... they would be by default 'Public'. If nothing is specified in the abstract class it would be 'Private'(In regards to members of the interface/abstract class only).
An interface is used when you want your class to be able to do something.
Your class extends an abstract class when there is a 'is a' relationship.
There is a semantic difference.
In case of abstract class.
class Dog : abstractAnimal
When we create object of Dog, we will have to create object of abstractAnimal to, it will lead to extra object creation.
In case of interface.
class Dog : IAnimal
When we create object of Dog, we will not be creating any extra object of anything.
In that case you can say:
1) We can specify different access modifier to methods present in class,
but we can't change access modifier of Interface member.
2) Derived class from abstract will not have a compulsion of
implementation.
As we know there are basically two important difference between Interface and Abstract class.
We can have function definitions in abstract class. This is advantageous when we want to add a function in a class without need to track down it's all implementations.
We can have multiple interface implementation.
I just came to know that we can differentiate between them in terms of Decoupling?
Your comments...
Also if you can you provide a very basic link that explains the Decoupling for Interface and Abstract class ?
We normally use Business Logic Layer, Data Access Layer(contains abstract functions) and DataAccess.SqlServer Layer. Right? Despite of the fact that we aware of the Business needs, why are we creating Data Access Layer(contains abstract functions), Why can't Business Logic layer directly access DataAccess.SqlServer Layer?
Decoupling
In programming and design, this is generally the act of making code which is re-usable with as few dependencies as possible.
Factory Pattern In This Context
When using the Factory Pattern, you have a centralized factory which can create objects without necessarily defining them itself. That would be up to the object's definition.
Abstract and Interface
Interface
Defining an interface is best practice, as it allows for a light weight type to be used for inference, and also provides a blueprint which all inheriting classes must abide by. For example, IDisposable must implement the Dispose method. Note that this is decoupled from the interface, as each class inheriting IDisposable will define its own function of the Dispose method.
Abstract
Abstract is similar to interface in that it is used for inheritance and inference, but it contains definitions which all classes will inherit. Something to the extent of every automobile will have an engine so a good abstract class for automobile could include a predefined set of methods for an engine.
Edit
Explanation
Here you will see a simple example of inheritance using an interface and an abstract class. The decoupling occurs when the interface is inherited by an abstract class and then it's methods are customized. This allows for a class to inherit the abstract class and still have the same type as the interface. The advantage is that the class inheriting the abstract class can be used when the expected type is the original interface.
Decoupling
That advantage allows for any implementation to be used which conforms to the expected interface. As such, many different overloads can be written and passed in. Here is an example of one.
Example
Interface Definition
public interface IReady
{
bool ComputeReadiness();
}
Inheritance
public abstract class WidgetExample : IReady
{
public int WidgetCount { get; set; }
public int WidgetTarget { get; set; }
public bool WidgetsReady { get; set; }
public WidgetExample()
{
WidgetCount = 3;
WidgetTarget = 45;
}
public bool ComputeReadiness()
{
if (WidgetCount < WidgetTarget)
{
WidgetsReady = false;
}
return WidgetsReady;
}
}
public class Foo : WidgetExample
{
public Foo()
{
this.WidgetTarget = 2;
}
}
public class Bar : IReady
{
public bool ComputeReadiness()
{
return true;
}
}
Decoupling
public class UsesIReady
{
public bool Start { get; set; }
public List<string> WidgetNames { get; set; }
//Here is the decoupling. Note that any object passed
//in with type IReady will be accepted in this method
public void BeginWork(IReady readiness)
{
if (readiness.ComputeReadiness())
{
Start = true;
Work();
}
}
private void Work()
{
foreach( var name in WidgetNames )
{
//todo: build name
}
}
}
Polymorphism
public class Main
{
public Main()
{
//Notice that either one of these implementations
//is accepted by BeginWork
//Foo uses the abstract class
IReady example = new Foo();
UsesIReady workExample = new UsesIReady();
workExample.BeginWork(example);
//Bar uses the interface
IReady sample = new Bar();
UsesIReady workSample = new UsesIReady();
workSample.BeginWork(sample);
}
}
I've been looking through the answers, and they all seem a little complicated for the question. So here is my (hopefully) simpler answer.
Interface should be used when none of the implementation details are available to the current scope of the code.
Abstracts should be used when some of the implementation details are available to you
And, for completeness, when all of the implementation details are available you should be using classes.
In terms of decoupling, while I somewhat agree with Shelakel, for the purposes of this question, and stating fully decoupled design practices, I would suggest the following:
Always use Interfaces to define external behaviour.
When you have some of the implementation details available, use
abstract classes to define them, but implement the interfaces on
the abstract classes, and inherit from those classes in turn.
This ensures that later if you need to change some obscure implementation detail in a new implementation you are able to do so without modifying the existing abstract class, and are also able to group different implementation types into different abstract classes.
EDIT: I forgot to include the link :)
http://www.codeproject.com/Articles/11155/Abstract-Class-versus-Interface
Abstract classes and interfaces are not MUTUALLY EXCLUSIVE choices. I often define both an Interface and an abstract class that implements that interface.
The interface ensure the maximum decoupling because it doesnt force your class to belong to a specific inheritance hierarchy, so your class may inherit from whichever other class. In other terms any class can inherit from an Interface, while classes that already inherits from other classes cannot inherit from an abstract class.
On the other side in an abstract class you can factor out code that is common to all implementations, while with Interfaces you are forced to implement everything from the scratch.
As a conclusion, often the best solution is using BOTH an abstract class and an Interface, so one can move from re-using the common code contained in the abstract class, if possible, to re-implementing the interface from the scratch, if needed.
Decoupling for the sake of decoupling is a futile exercise.
Interfaces are meant to be used for integration where the specifics aren't required to be known to be of use (ex. SendEmail()). Common uses include components, services, repositories and as markers for IOC and generic implementations.
Extension methods with generic type constraints that include interfaces allow functionality similar to traits found in Scala with similar composability.
public interface IHasQuantity { double Quantity { get; } }
public interface IHasPrice { decimal PricePerUnit { get; } }
public static class TraitExtensions
{
public static decimal CalculateTotalPrice<T>(this T instance)
where T : class, IHasPrice, IHasQuantity
{
return (decimal)instance.Quantity * instance.PricePerQuantity;
}
}
In my opinion, abstract classes and class inheritance is overused.
SOLID design principles teach us that Liskov's substitution principle implies that class inheritance should only be used if the inherited class is substitutable for the ancestor. This means that all methods should be implemented (no throw new NotImplementedExeption()) and should behave as expected.
I personally have found class inheritance useful in the case of the Template Method pattern as well as for state machines. Design patterns such as the builder pattern are in most cases more useful than deep chains of inheritance.
Now back to your question; interfaces should be used most if not all of the time. Class inheritance should be used internally and only externally for purposes of definition, whereafter an interface should be used for interaction and the concrete implementation provided via a factory or to be injected via an IOC container.
Ideally when using external libraries, an interface should be created and an adapter implemented to expose only the functionality required. Most of these components allow to be configured beforehand or at runtime to be resolved via an IOC container.
In terms of decoupling, it is important to decouple the application from its implementations (especially external dependencies) to minimize the reasons to change.
I hope that my explanation points you in the right direction. Remember that it's preferred to refactor working implementations and thereafter interfaces are defined to expose functionality.
I'm not going to discuss what are the pros/cons of these two constructs in general, as there are enough resources on that.
However, In terms of 'decoupling' a component from another, interface inheritance is much better than abstract classes, or class inheritance in general (In fact I don't think being abstract or not does not make much difference in terms of decoupling as all abstract does is prevent the class being instantiated without a concrete implementation).
Reason for above argument is, interfaces allow you to narrow down the exposure to absolute minimum of what required by the 'dependent component', if it requires a single method interface can easily do that, or even be a marker interface without any method. This might be difficult with a base class (abstract or concrete) as it should implement all the 'common' functionality for that base. Because of this a component dependent on the 'base type' will automatically 'see' all the common functionality even it does not need them for it's purposes.
Interfaces also gives you the best flexibility as even classes inheriting from bases which have nothing in common, can still implement an interface, and be used by the component expecting that interface. Good example of this is IDisposable interface.
So, my conclusion is for decoupling concern have all your components depend on interfaces than base types, and if you find most of your classes implementing that interface has a common implementation then have a base class implementing that interface and inherit other classes from that base.
The core difference is this:
Interfaces expose zero or more method signatures which all descendants must in turn implement (otherwise code won't even compile).
Interface-exposed methods can either be implemented implicitly (every type derived from the interface has access to them) or explicitely (methods can be accessed only if you typecast the object to the interface type itself). More details and an example can be found in this question.
Abstract classes expose zero or more full-fledged methods, which descendants can either use or override, providing their own implementation. This approach allows you to define a customizable, "default" behavior. Abstract classes allows you to easily add new methods with no issues (NotImplementedException really shines when adding methods to abstract classes), whereas adding a method to an interface requires you to modify all the classes implementing it.
The final point is, that a class can implement more than one interface simultaneously.
Some real-world example might be:
A hard drive which provides both USB and LAN ports is a good demonstration of multiple interface inheritance
A Laptop which has a LED marked "bluetooth" but no bluetooth hardware on board is a good analogy of the concept of not implementing an abstract method (you have the LED, you have the little B symbol, but there's nothing under the roof).
Edit 1
Here's a MSDN link explaining how to choose between interface and classes.
Defining a contract using an abstract class means that your implementers must inherit from this abstract class. Since C# doesn't support multiple inheritance, these implementers will not be able to have an alternate class hierarchy, which can be pretty limiting for some. In other words, an abstract class basically otherwise robs the implementer of the class hierarchy feature, which is often needed to get or use some other capabilities (of a framework or class library).
Defining a contract using an interface leaves the class hierarchy free for your implementers to use any way they see fit, in other words, providing much more freedom of implementation.
From a perspective of evaluation criteria, when we talk about coupling here we can speak to concerns of three separable authors, the client using (calling) the API/contract, the definer of the API/contract, and the implementer of the API/contract; we can speak to freedom (the fewer restrictions, the better), encapsulation (the less awareness necessary, the better), and resilience in the face of change.
I would offer that an interface results in looser coupling than an abstract class, in particular, between the definer and the implementer, due to higher freedom offered the implementer.
On the other hand, when it comes to versioning, you can at least add another method to the abstract class without necessarily requiring updates to subclass implementations, provided the added method has an implementation in the abstract class. Versioning interfaces across DLL boundaries usually means adding another interface, much more complex to roll out. (Of course, this is not a concern if you can refactor all the implementations together (say, because they're all in the same DLL)).
The best way to understand and remember difference between interface and abstract class, it's to remember that abstract class is a normal class and you can do everything with abstract class that you can do with the normal class with two exceptions.
You can't instantiate an abstract class
You can have abstract method only in abstract class
Coding to interface provides reusability and polymorphism.As far as class implements interface,the interface or abstract class can be passed to parameter instead of class that implements the interface.Urs common technical problem is handled vis designing interface and abstract class and implementing it and giving subclass the specific functionality implementation.Imagine its like framework.Framework define interface and abstract class and implement it that is common to all.And those that are abstract is implemented by client according to its own requirement.
public interface Polymorphism{
void run();
Void Bark();
Energy getEnergy(Polymorphism test);
Public abstract class EnergySynthesis implements Polymorphism{
abstract void Energy();
Void Bark(){
getEnergy(){
}
void run(){
getEnergy();
}public EnegyGeneartion extends EnergySynthesis {
Energy getEnergy(Polymorphism test){
return new Energy( test);
}
MainClass{
EnegyGeneartion test=new EnegyGeneartion ();
test.getEnergy(test);
test.Bark()
.
.
.
.
.
//here in Energy getEnergy(Polymorphism test) any class can be passed as parameter that implemets interface
For my new Pet-Project I have a question for design, that is decided already, but I want some other opinions on that too.
I have two classes (simplified):
class MyObject
{
string name {get;set;}
enum relation {get;set;}
int value {get;set;}
}
class MyObjectGroup
{
string name {get;set;}
enum relation {get;set;}
int value {get;set;}
List<MyObject> myobjects {get;set;}
}
Later in the Project MyObjectGroup and MyObject should be used equally. For this I could go two ways:
Create an interface: IObject
Create an abstract class: ObjectBase
I decided to go the way of the interface, that I later in code must not write ObjectBase every time but IObject just for ease - but what are other positives for this way?
And second, what about adding IXmlSerializable to the whole story?
Let the interface inherit from IXmlSerializable or does it have more positives to implement IXmlSerializable in abstract base class?
Generally speaking, the approach I use in this kind of situation is to have both an interface and an abstract class. The interfaces defines, well, the interface. The abstract class is merely a helper.
You really can't go wrong with this approach. Interfaces give you the flexibility to change implementation. Abstract classes give you boilerplate and helper code that you aren't forced to use, which you otherwise would be if your methods were defined in terms of an abstract class explicitly.
These are some of the differences between Interfaces and Abstract classes.
1A. A class may inherit (Implement) one or more interfaces. So in C#, interfaces are used to achieve multiple inheritance.
1B. A class may inherit only one abstract class.
2A. An interface cannot provide any code, just the signature.
2B. An abstract class can provide complete, default code and/or just the details that have to be overridden.
3A. An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public.
3B. An abstract class can contain access modifiers for the subs, functions, properties.
4A. Interfaces are used to define the peripheral abilities of a class. For eg. A Ship and a Car can implement a IMovable interface.
4B. An abstract class defines the core identity of a class and there it is used for objects.
5A. If various implementations only share method signatures then it is better to use Interfaces.
5B. If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
6A. If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
6B. 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.
7A. An interface can not have fields defined.
7B. An abstract class can have fields and constants defined.
8A. An interface can not have constructor.
8B. An abstract class can have default constructors implemented.
9A. An interface can only inherit from other interfaces.
9B. An abstract class can inherit from interfaces, abstract class, or even class.
The interface would be my default until there is a reason to use a base class, as it makes fewer decisions for us.
I wouldn't involve IXmlSerializable unless I had to though; it is a messy, tricky interface that is often a cause of woe.
What exactly are your serialization requirements? There may be better options... however, for many serializers a base-class would be easier than an interface. For example, for XmlSerializer you could have:
[XmlInclude(typeof(MyObject))] // : ObjectBase
[XmlInclude(typeof(MyObjectGroup))] // : ObjectBase
public abstract class ObjectBase { /* */ }
(the exact approach depends on the serializer)
Generally, you should consider interfaces as contracts that some types implement and abstract classes as nodes in inheritance hierarchy that don't exist by themselves (i.e. there is an "is a" relationship between the derived class and the base abstract class). However, in practice, you might need to use interfaces in other cases, like when you need multiple inheritance.
For instance, IXmlSerializable is not an "entity" by itself. It defines a contract that an entity can implement. Interfaces live "outside" the inheritance hierarchy.
An Interface will allow you to define a 'contract' that the object will need to fulfil by delivering properties and methods as described by the interface. You can refer to objects by variables of interface-type which can cause some confusion as to what exactly is being offered.
A base class offers the opportunity to build an inheritance 'tree' where more complex classes (of a common 'type') are built on the foundations of a simpler 'base' classes. The classic and annoying example in OO is normally a base class of 'Shape' and which is inherited by Triangle, Square, etc.
The main point is that with an Interface you need to provide the entire contract with every class that implements it, with an inheritance tree (base classes) you are only changing/adding the properties and methods that are unique to the child class, common properties and methods remain in the base class.
In your example above I'd have the 'MyObjectGroup' object inherit the base 'MyObject' class, nothing to be gained from an interface here that I can see.
There are two thing is in Architect’s mind when designing classes.
Behavior of an object.
object’s implementation.
If an entity has more than one implementation, then separating the behavior of an object from its implementation is one of the key for maintainability and decoupling.
Separation can be achieved by either Abstract class or Interface but which one is the best? Lets take an example to check this.
Lets take a development scenario where things (request, class model, etc) are changing very frequently and you have to deliver certain versions of application.
Initial problem statement : you have to create a “Train” class for Indian railway which has behavior of maxSpeed in 1970 .
1. Business Modeling with abstract class
V 0.0 (Initial problem)
Initial problem statement : you have to create a Train class for Indian railway which has behavior of maxSpeed in 1970 .
public abstract class Train {
public int maxSpeed();
}
V 1.0 (Changed problem 1)
changed problem statement : You have to create a Diesel Train class for Indian railway which has behavior of maxSpeed, in 1975.
public abstract class DieselTrain extends train {
public int maxFuelCapacity ();
}
V 2.0 (Changed problem 2)
chanded problem statement : you have to create a ElectricalTrain class for Indian railway which has behavior of maxSpeed , maxVoltage in 1980.
public abstract class ElectricalTrain extends train {
public int maxvoltage ();
}
V 3.0 (Changed problem 3 )
chanded problem statement : you have to create a HybridTrain (uses both diesel and electrcity) class for Indian railway which has behavior of maxSpeed , maxVoltage,maxVoltage in 1985 .
public abstract class HybridTrain extends ElectricalTrain , DisealTrain {
{ Not possible in java }
}
{here Business modeling with abstract class fails}
2. Business Modeling with interface
Just change abstract word to interface and ……
your Business Modeling with interface will succeeds.
http://javaqna.wordpress.com/2008/08/24/why-the-use-on-interfaces-instead-of-abstract-classes-is-encouraged-in-java-programming/
Interface:
If your child classes should all implement a certain group of methods/functionalities but each of the child classes is free to provide its own implementation then use interfaces.
For e.g. if you are implementing a class hierarchy for vehicles implement an interface called Vehicle which has properties like Colour MaxSpeed etc. and methods like Drive(). All child classes like Car Scooter AirPlane SolarCar etc. should derive from this base interface but provide a seperate implementation of the methods and properties exposed by Vehicle.
–> If you want your child classes to implement multiple unrelated functionalities in short multiple inheritance use interfaces.
For e.g. if you are implementing a class called SpaceShip that has to have functionalities from a Vehicle as well as that from a UFO then make both Vehicle and UFO as interfaces and then create a class SpaceShip that implements both Vehicle and UFO .
Abstract Classes:
–> When you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.
For e.g. again take the example of the Vehicle class above. If we want all classes deriving from Vehicle to implement the Drive() method in a fixed way whereas the other methods can be overridden by child classes. In such a scenario we implement the Vehicle class as an abstract class with an implementation of Drive while leave the other methods / properties as abstract so they could be overridden by child classes.
–> The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.
For example a class library may define an abstract class that is used as a parameter to many of its functions and require programmers using that library to provide their own implementation of the class by creating a derived class.
You could actually go with BOTH. ObjectBase saves you the trouble of implementing the common properties more than once and implements IObject for you. Everywhere you use it refer to IObject so you can do testing with mocks later
I'd rather go for base abstract class, because, theoretically (well, it's just one theory, I'm not proving or saying that any other is worse then this) - interfaces should be used, when you want to show, that some object is capable of doing something (like IComparable - you show that whatever implements it, can be compared to something else), whereas when you have 2 instances that just share something common or have 1 logical parent - abstract classes should be used.
You could also go for both approaches, using base class, that will implement an interface, that will explicitly point what your class can do.
Note that you cannot override operators in Interfaces. That is the only real problem with them as far as I'm concerned.
All else being equal, go with the interface. Easier to mock out for unit testing.
But generally, all I use base classes for is when there's some common code that I'd rather put in one place, rather than each instance of the derived class. If it's for something like what you're describing, where the way they're used is the same, but their underlying mechanics are different, an interface sounds more appropriate.
I've been using abstract classes in my projects, but in future projects, I'll use interfaces.
The advantage of "multiple inheritance" is extremely useful.
Having the ability to provide a completely new implementation of the class, both in code, or for testing purposes, is always welcome.
Lastly, if in the future you'll want to have the ability to customize your code by external developers, you don't have to give them your real code - they can just use the interfaces...
If you have function in class,you should use abstact class instead of interface.
In general,an interface is used to be on behalf of a type.
Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks.
Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, Java calls the method defined by the child class.
Many developers forget that a class that defines an abstract method can call that method as well. Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies.
The definition of the abstract class may describe code and state, and classes that derive from them may not derive from other classes at the same time. That's what the technical difference is.
Therefore, from the point of view of usage & philosophy, the difference is that by setting up an abstract class, you constrain any other functionality that the objects of that class may implement, and provide those objects with some basic functionality that is common for any such object (which is a kind of constraint, too), while by setting up an interface, you set up no constraints for other functionality and make no real-code provisions for that functionality which you have in mind. Use the abstract classes when you about know everything that objects of this class are supposed to be doing for the benefit of their users. Use the interfaces when the objects might also do something else that you can't even guess by now.