Confuesd about abstract class vs interface

P

phl

hi,

I am kind of confused aobut interfaces and abstract classes.

In short as I understand it, an interface is like a contract between
the class and the interface, so that certain funtions must be
implemented. So if you have a class which inherits base class that
inherts an interface, then your classes will have a standard. I suppose
you can also check for interface at run time say when dll is loaded and
see if it implememts whats required by interface also before loading
it.

I have never used abstract classes, as I understand it, its for
creating a base class with function without any implementation, so that
it can be done in your inherited class. I am confused why you would
need this, as you already can override functions and also theres
interfaces.

I have probably misunderstood something, can someone please explain.
The reason i am interested is because I am writing a system which i
hope to be well maintained in the future. I want other people to add
classes with specific implementations.

thanks
 
C

cody

An abstract base class is useful if you want that this class and its
descendentants cannot be instantiated unless they override *all* abstract
methods:

abstract class Foo
{
abstract void DoFoo();
}

abstract class A : Foo
{
}

class B : Foo
{
override void DoFoo();
}

You cannot create instances from A because the class did not implement to
DoFoo() method, therefore it has to be declared abstract. But you can create
instances from B since it implements DoFoo() so that is does not have to be
abstract anymore.
 
B

Bob Powell [MVP]

An interface is a facade that can be placed on any class to make it conform
to a specific set of behaviours. Any class can implement any interface and
this is particularly useful in a componentised and extensible system in
which you're not sure what classes might be used by the system in the
future.

A prime example of this is the IEnumerable interface. Any class, it doesn't
even have to be a collection class, can be enumerable. The class might
synthesize some data and masquerade as a collection.

Abstract classes however are of prime importance if you need to enforce at
least which base-class is used in the derivation process.
System.Drawing.Image for example, is an abstract class and objects with the
declared type of image are used all the time. The real object will probably
be a Bitmap, which is derived from Image, but the base-class type is
enforced. The requirements of an abstract class are that the abstract
implementation MUST be provided. This enables the architect to enforce
certain rules about the class structure without having to interpret all
possible cases for implementation in advance.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
 
M

MaSTeR

cody said:
An abstract base class is useful if you want that this class and its
descendentants cannot be instantiated unless they override *all* abstract
methods:

abstract class Foo
{
abstract void DoFoo();
}

abstract class A : Foo
{
}

class B : Foo
{
override void DoFoo();
}

You cannot create instances from A because the class did not implement to
DoFoo() method, therefore it has to be declared abstract. But you can create
instances from B since it implements DoFoo() so that is does not have to be
abstract anymore.


--

Same with interfaces.
 
M

MaSTeR

I am kind of confused aobut interfaces and abstract classes.
In short as I understand it, an interface is like a contract between
the class and the interface, so that certain funtions must be
implemented. So if you have a class which inherits base class that
inherts an interface, then your classes will have a standard. I suppose
you can also check for interface at run time say when dll is loaded and
see if it implememts whats required by interface also before loading
it.

I have never used abstract classes, as I understand it, its for
creating a base class with function without any implementation, so that
it can be done in your inherited class. I am confused why you would
need this, as you already can override functions and also theres
interfaces.

I have probably misunderstood something, can someone please explain.
The reason i am interested is because I am writing a system which i
hope to be well maintained in the future. I want other people to add
classes with specific implementations.

thanks

If you create an abstract class with no method implementation and no data
members it is pretty much the same as defining an interface, no wonder why
in COM interfaces are implemented like that.

HOWEVER.

There are a number of differences.
-In abstract classes you can have data members to keep, for instance,
internal state

-In abstract classes you can provide implementation for a method:
say you have a Vehicle abstract class, you can derive Bike, MotorCycle and
Car from that, but you might want to define a method GetCC() in the base
class that will never change (no can do with interfaces)

-last but not least a C# object can implement as many interface you want but
can just inherit from one class.

Hope this helps.
 
H

Hans Kesting

phl said:
hi,

I am kind of confused aobut interfaces and abstract classes.

In short as I understand it, an interface is like a contract between
the class and the interface, so that certain funtions must be
implemented. So if you have a class which inherits base class that
inherts an interface, then your classes will have a standard. I
suppose you can also check for interface at run time say when dll is
loaded and see if it implememts whats required by interface also
before loading it.

I have never used abstract classes, as I understand it, its for
creating a base class with function without any implementation, so
that it can be done in your inherited class. I am confused why you
would need this, as you already can override functions and also theres
interfaces.

I have probably misunderstood something, can someone please explain.
The reason i am interested is because I am writing a system which i
hope to be well maintained in the future. I want other people to add
classes with specific implementations.

thanks

If some class implements an interface, it declares that it (at least) has the
methods (and properties) declared in the interface. It *acts like* it
is that interface type.

If a class extends some (possibly abstract) baseclass it has some
basic functionality, plus there are some other methods that need to
be filled in. It *is a version* of that type.

Hans Kesting
 
C

Chuck Bowling

An abstract class is kind of like a new car. You start out with a basic no
frills car (your abstract class), then you add too it - superduper radio,
custom paint, nice wheels. That's inheritance. You inherited the basic car
and added features via your inheriting class.

An interface is a promise that your class will implement a set of methods
specified by the interface. An instance of a class that uses another class
containing an interface knows that it can rely on that class to provide
functions promised by the interface.
 
C

cody

If you implement an interface you have to provide all methods is your class,
otherwise your code won't compile.
When using an abstract baseclass you can compile your code even when you
don't provide all abstract methods in your code - but in this case you have
to declare your class abstract and therefore cannot instantiate it.
 
B

Bruce Wood

Looking at the other responses here, I think that what's missing is an
explanation of when and why you would use an abstract class versus an
interface.

You need an interface if you want to assign common behaviour to various
classes that do not derive from the same base class (other than
Object). Bob Powell gave the excellent example of IEnumerable: you want
to be able to make many classes from all over the class hierarchy
enumerable, and in some methods treat them as "the same" for purposes
of enumeration, even though they're otherwise completely different
classes that have nothing in common.

This is different from the classic LivingThing / Animal / Mammal / Dog
/ Corgi relationship, in which the classes in the list have an "is-a"
relationship. In the world of living things, for example, you could
decide that you want some methods to be able to work with animals that
can walk. You can't have those methods accept Animal objects, because
some animals don't have legs and so cannot walk (snakes, fish, whales,
etc). So, you would need an IWalkable interface that you implement only
in certain classes (such as Dog), but where the classes that implement
it are not necessarily cleanly related in your hierarchy.

Of course, if any class implements IWalkable, this means that all of
its child classes automatically implement IWalkable by inheritance. So,
implementing IWalkable in Dog means that all types of dogs are
walkable, no matter what you do in the classes for particular breeds of
dogs.

An abstract base class is needed in a different situation. Some times
you can write most of the implementation of a class but not all of it.
Or, to look at it from the opposite point of view, perhaps you have
some classes that have a lot in common, and could really use a parent
class, but some of the methods and/or properties don't generalize well.
Again, Bob Powell gave the example of Image. There are lots of
different kinds of images: bit maps, jpegs, gifs, tiffs, etc. You want
all of those kinds of images to have (mostly) the same methods and
properties, for example you want them all to have a RotateFlip() method
to allow the caller to rotate the image, but you can't write a
meaningful implementation for that method until you know what kind of
image you're dealing with.

Without abstract base classes, you're stuck with a dilemma. If you
don't write a RotateFlip() method in the base class, then even if all
child classes declare and implement a RotateFlip() method, you won't be
able to call any of those methods if you're dealing with the Bitmap
object (for example) downcast to an Image, because Image doesn't have
that method. Or, if you implement a dummy version of the method in the
base class and someone declares a new type of Image and forgets to
override the method, then you're stuck with an Image subclass that
calls back to the dummy method that doesn't really work (because it
doesn't know how the image is represented). You could solve the problem
by adding an IRotateable interface, and insisting that all of your
child classes implement it, but now you have a base class _and_ an
interface. Yuck.

Abstract classes solve this problem nicely. They say, "There is a group
of things called Images that exhibit this behaviour. However, I can't
tell you _how_ those things _implement_ some parts of this behaviour.
That's up to my child classes."

Of course, as some people pointed out, you could create the same
external functionality by using an interface rather than an abstract
base class, but this has one enormous disadvantage: if a lot of (or
even a little of) the _implementation_ of the behaviour of an image, or
the state it needs to store, is common to all of the different kinds of
Images, then with an interface you have to repeat that code in every
subclass: you can't inherit an implementation through an interface, you
can inherit only the contract.
 
R

Ravichandran J.V.

B

Bruce Wood

It's a fine point, I know, but that is not strictly true.

Interfaces do not allow the definition of any member (except maybe
constants--I'm not sure about constants) because interfaces are
strictly for _declaring_ things, not _defining_ them. The class that
implements the interface must define the members declared in the
interface.

Abstract classes can define anything they like. Defined members in
abstract classes do _not_ have to be virtual or static, although they
can be. They can also be boring, ordinary methods at any protection
level. The only requirement of having an abstract class is that _at
least one_ member must remain undefined, or "abstract", to be defined
by classes that inherit from the abstract class.

However, to reiterate, an abstract class can define all sorts of
members: public, protected, private, virtual, static, final... you name
it. So long as there is at least one abstract member (property or
method), the class is abstract and cannot be instantiated.
 
J

Jeff Louie

There is very little difference between a _pure virtual_ abstract class
and an
interface except that I believe the extra overhead of the V table lookup
with
the abstract class (I could be wrong about that) and the fact that you
can only
inherit from one abstract class. So the major difference between an
abstract
class and an interface is that you can have implementation details in
the
abstract class. If you need to define a contract but do not need to
include any
implementation details you are probably better off using an interface.
If you
must include some implementation details, then you are pretty much stuck
with an abstract class. Of course, you can combine these approaches by
defining an interface and providing an abstract class with default
implementations of the interface. I have sample code of this on my
website.

Regards,
Jeff
 
B

Bruce Wood

Of course, you can combine these approaches by
defining an interface and providing an abstract class with default
implementations of the interface. I have sample code of this on my
website.

Yes, the .NET Framework does this in places, too. This is an especially
good idea (and especially kind to poor developers) if you do this in an
API that you sell. It's much more pleasant to have a "ready-made"
implementation of an interface to draw on.
 
B

Bruce Wood

Jeff, I suspect that interfaces, too, require a V table lookup. Because
the compiler cannot know at compile time which class is assigned to a
variable of type IEnumerable, for example, it has to have a V table at
its disposal at run time in order to find the relevant methods, it
cannot compile in a direct call to the method, because the location of
the method depends upon the implementing class.

I'm no CLR guru, so I may be blowing smoke here. I'm just reasoning
from first principles. Please do correct me if I'm wrong.
 
J

Jeff Louie

Hi Bruce.. Can't look for the article since I am off skiing, but C++UJ
had an
article which explored the use of C++ interfaces suggesting that they
would
be more efficient than multiple inheritance of pure virtual classes.

Regards,
Jeff
Jeff, I suspect that interfaces, too, require a V table lookup.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top