By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,900 Members | 1,367 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,900 IT Pros & Developers. It's quick & easy.

interface question

P: n/a
Hi all. I have a question about interfaces now. According to the book
I'm reading, when you implement an interface, the class or structure
has to declare all the methods that the interface includes.

My question is, if you must declare each method (as opposed to simply
'using' those methods like an #included file), then why not just
declare the methods on your own as if you created them yourself? What
advantage does using an interface have if you must manually declare
all the methods anyway?

Thanks.
Nov 17 '05 #1
Share this Question
Share on Google+
13 Replies


P: n/a
> My question is, if you must declare each method (as opposed to simply
'using' those methods like an #included file), then why not just
declare the methods on your own as if you created them yourself? What advantage does using an interface have if you must manually declare
all the methods anyway?


The answer is something called "polymorphism": if you declare a bunch
of classes as implementing the same interface, then you can write code
that can operate on any of those classes, because the code knows that
they all implement the same interface methods with the same calling
sequences (signatures). As a (stupid) example, if I were to have an
interface:

public interface IGreeting
{
public string Hello { get; }
public void ShakeHands();
}

and I write a couple of classes:

public class English : IGreeting
{
public string Hello { get { return "Hello"; } }
public void ShakeHands() { // Do some stuff here }
}

public class Spanish : IGreeting
{
public string Hello { get { return "Buenos días"; } }
public void ShakeHands() { // Do some stuff here }
}

then I could write a method in some other class:

public void SayHello(IGreeting person)
{
Console.WriteLine(person.Hello);
person.ShakeHands();
}

"SayHello" can say hello and shake hands without knowing what kind of
person it is, because it knows that all objects passed to it must
implement the IGreeting interface, and so must have a "Hello" string
property and a "ShakeHands" method that takes no arguments.

Without the interface, there would be no way to express, "An object
that has a Hello string property and a ShakeHands void method that
takes no arguments."

(By the way, a picky detail about terminology: the interface _declares_
the properties, methods, and events. The class either _implements_ them
or _defines_ them (they both mean the same thing, really). Yes, the
class also declares them again, but that's not so important as the idea
that it implements them.)

Nov 17 '05 #2

P: n/a
Here is a real world example of how you might utilize interfaces:

http://www.eggheadcafe.com/articles/20031103.asp

--
2004 and 2005 Microsoft MVP C#
Robbe Morris
http://www.robbemorris.com
http://www.masterado.net/home/listings.aspx

"John Salerno" <jo******@NOSPAMgmail.com> wrote in message
news:EN********************@rcn.net...
Hi all. I have a question about interfaces now. According to the book
I'm reading, when you implement an interface, the class or structure
has to declare all the methods that the interface includes.

My question is, if you must declare each method (as opposed to simply
'using' those methods like an #included file), then why not just
declare the methods on your own as if you created them yourself? What
advantage does using an interface have if you must manually declare
all the methods anyway?

Thanks.

Nov 17 '05 #3

P: n/a
Thanks Bruce. This is a timely topic for me.

The SayHello method signature includes a person parameter of type IGreeting.
If the person parameter is an object of type IGreeting where does the person
object get its string data that is then passed through as a value to the
person.Hello parameter of the WriteLine method?

<%= Clinton Gallagher
"Bruce Wood" <br*******@canada.com> wrote in message
news:11*********************@f14g2000cwb.googlegro ups.com...
My question is, if you must declare each method (as opposed to simply 'using' those methods like an #included file), then why not just
declare the methods on your own as if you created them yourself? What advantage does using an interface have if you must manually declare
all the methods anyway?


The answer is something called "polymorphism": if you declare a bunch
of classes as implementing the same interface, then you can write code
that can operate on any of those classes, because the code knows that
they all implement the same interface methods with the same calling
sequences (signatures). As a (stupid) example, if I were to have an
interface:

public interface IGreeting
{
public string Hello { get; }
public void ShakeHands();
}

and I write a couple of classes:

public class English : IGreeting
{
public string Hello { get { return "Hello"; } }
public void ShakeHands() { // Do some stuff here }
}

public class Spanish : IGreeting
{
public string Hello { get { return "Buenos días"; } }
public void ShakeHands() { // Do some stuff here }
}

then I could write a method in some other class:

public void SayHello(IGreeting person)
{
Console.WriteLine(person.Hello);
person.ShakeHands();
}

"SayHello" can say hello and shake hands without knowing what kind of
person it is, because it knows that all objects passed to it must
implement the IGreeting interface, and so must have a "Hello" string
property and a "ShakeHands" method that takes no arguments.

Without the interface, there would be no way to express, "An object
that has a Hello string property and a ShakeHands void method that
takes no arguments."

(By the way, a picky detail about terminology: the interface _declares_
the properties, methods, and events. The class either _implements_ them
or _defines_ them (they both mean the same thing, really). Yes, the
class also declares them again, but that's not so important as the idea
that it implements them.)
Nov 17 '05 #4

P: n/a
I can think of at least four reasons to use an interface or abstract
class:

1) Defer the Final Implementation to Another More Knowledgeable Class

2) Formally Hide or Encapsulate the Implementation for Flexibility

3) Allow Runtime Variation in Implementation (Polymorphism)

4) Mark Thyself

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #5

P: n/a
Think of it this way.

The SayHello method doesn't accept a person parameter of type
IGreeting. It accepts any object that implements the IGreeting
interface. That is, you can't create an object that is just an
IGreeting, because IGreeting is an interface, not a class. So, "person"
must be, in reality (at run time), an instance of some class, such as
the English and Spanish classes that I defined in the example.

What the "IGreeting person" says is, "I will accept any object, but it
must be an object that implements the methods, properties, and events
declared in the IGreeting interface."

So, you would call SayHello like this:

English mortimer = new English();
SayHello(mortimer);

or like this:

Spanish luis = new Spanish();
SayHello(luis);

The first SayHello call will write "Hello", the second will write
"Buenos días". (This example is getting sillier by the minute, isn't
it? :) This happens because the English class defines its Hello
property to return the string "Hello", while the Spanish class defines
that same property to return "Buenos días". The SayHello method can
refer to the property in either class because the two classes implement
the same interface.

This is called "polymorphism": the two classes English and Spanish may
be completely unrelated. They may have no common base class, and may
have no other methods in common. However, because they both implement
IGreeting, they guarantee that they both at least have the Hello
property and the ShakeHands() method. Therefore, methods like
SayHello() that take as their arguments "anything that implements
IGreeting" can accept completely different objects (thus "polymorphic":
"different shapes"), so long as their classes implement the required
interface.

Nov 17 '05 #6

P: n/a
The distinction between abstract class and interface is an important
one and helps highlight situations in which you need to use an
interface.

An abstract base class is useful in situations where you have two or
more distinct things that are nonetheless of the same "type of thing":
they all have an "is-a" relationship with a common class which,
nonetheless, isn't a read business entity, so you would never want to
make one.

A good example came up recently in this newsgroup: someone had two
kinds of sales orders, a "T" order and an "S" order (or something like
that). Both of them are sales orders, but neither is subordinate to the
other (the "T" order is not just a specialized kind of "S" order, nor
the "S" order a specialized kind of "T" order). In this situation you
create a base class called SalesOrder that contains common code, and
make TSalesOrder and SSalesOrder subclasses of that base class. You
make SalesOrder abstract if all sales orders must be either
TSalesOrders or SSalesOrders... that is, if it makes no sense to create
a SalesOrder that isn't one of these two.

An interface is a different kind of beast. Sometimes you have a number
of classes that have no logical relationship. They don't have an "is a"
relationship, or an aggregation relationship, or anything like that.
However, they do share functionality. The classic example is that some
O-O languages don't have the ToString() method defined in the Object
class, so not every object automatically knows how to display itself as
a string. Or, you may have a language like C++ that has no common
Object base class. However, you still want all of your objects to be
able to implement ToString(). The objects that want to implement this
method have nothing to do with each other. They may be Forms,
SalesOrders, Users, Companies, Images, ... but they all want to
implement ToString(), and you want to write code that can display any
object. So, you use an interface. If a class implements, for example,
IPrintable, then you can trust that an object of that class has a
ToString() method that you can use to display its state.

Interfaces are needed where you want otherwise unrelated classes to
have some common behaviour.

Nov 17 '05 #7

P: n/a
ABC
One of the great uses of interfaces is in applications that have an Add-In
features. As Bruce said, members of interfaces can be used without requiring
us knowing what the objects that have implemented them actually do. This is
great, just imagine sth like this: You define the design of your application
through plenty of interfaces that each suggest a special functionality for
the class that implements it, then in another place, you implement those
interfaces and build up your application based on them. Now, you have
compiled the application; this design can be exploited by any developer who
wants to build an addin for your application and provide the same
functionality, or probably override some of the members and methods in your
application "after the compilation of your application". As you see, your
application for accepting the addins doesn't need to know what those addins
does. It rather expects them to implement the same set of interfaces that
the application itself has implemented.
A very nice example of this is "Luts Roeder's .NET Reflector" (
http://www.aisto.com/roeder/dotnet ). I recommand you disassemle the
reflector by usign itself to see what i say.
Nov 17 '05 #8

P: n/a
The mud is getting clearer all the time. Thanks for making these efforts to
explain this topic. I need to go practice what you've preached :-)

<%= Clinton Gallagher

"Bruce Wood" <br*******@canada.com> wrote in message
news:11*********************@g14g2000cwa.googlegro ups.com...
Think of it this way.

The SayHello method doesn't accept a person parameter of type
IGreeting. It accepts any object that implements the IGreeting
interface. That is, you can't create an object that is just an
IGreeting, because IGreeting is an interface, not a class. So, "person"
must be, in reality (at run time), an instance of some class, such as
the English and Spanish classes that I defined in the example.

What the "IGreeting person" says is, "I will accept any object, but it
must be an object that implements the methods, properties, and events
declared in the IGreeting interface."

So, you would call SayHello like this:

English mortimer = new English();
SayHello(mortimer);

or like this:

Spanish luis = new Spanish();
SayHello(luis);

The first SayHello call will write "Hello", the second will write
"Buenos días". (This example is getting sillier by the minute, isn't
it? :) This happens because the English class defines its Hello
property to return the string "Hello", while the Spanish class defines
that same property to return "Buenos días". The SayHello method can
refer to the property in either class because the two classes implement
the same interface.

This is called "polymorphism": the two classes English and Spanish may
be completely unrelated. They may have no common base class, and may
have no other methods in common. However, because they both implement
IGreeting, they guarantee that they both at least have the Hello
property and the ShakeHands() method. Therefore, methods like
SayHello() that take as their arguments "anything that implements
IGreeting" can accept completely different objects (thus "polymorphic":
"different shapes"), so long as their classes implement the required
interface.
Nov 17 '05 #9

P: n/a
I just disagree. IMHO an interface represents a subset of IS_A
relationships,
more specifically an abstract IS_A relationship. It provides the same
functionality as multiple inheritance of pure virtual abstract classes
in C++.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #10

P: n/a
"Jeff Louie" <an*******@devdex.com> a écrit dans le message de news:
O$**************@TK2MSFTNGP14.phx.gbl...
I just disagree. IMHO an interface represents a subset of IS_A
relationships,
more specifically an abstract IS_A relationship. It provides the same
functionality as multiple inheritance of pure virtual abstract classes
in C++.


Then you would be misdescribing an interface.

Take the classic multiple inheritance example of an amphibious vehicle.

By using MI, you are saying that an amphibious vehicle *is* a road vehicle,
and that it *is* a water vehicle. This is not strictly a correct analysis as
road vehicles don't have rudders and propellers; likewise water vehicles
don't have wheels and a steering rack to guide them.

More accurately, you can say that an amphibious vehicle is a class of
vehicle that is capable of *behaving like* a road vehicle or *behaving like*
a water vehicle. But these behaviours are not both possible at the same time
due to the limitations of environment that the vehicle finds itself in.

If MI were appropriate, then both behaviours would be available all the
time. Instead, we say that an amphibious vehicle implements two behaviours,
which can be selected according to the environment in which the vehicle
finds itself. It is no good me trying to use the wheels to drive in the sea,
neither is it any use trying to use the rudder to steer me around corners on
a road.

So :

class AmphibiousVehicle : Vehicle, IRoadVehicle, IWaterVehicle

....is more accurate than saying

class AmphibiousVehicle : RoadVehicle, WaterVehicle

Joanna

--
Joanna Carter
Consultant Software Engineer
Nov 17 '05 #11

P: n/a
Joanna... Again. I just disagree. IRoadVehicle and RoadVehicle are
functionally
equivalent in C++. The fact that you must use IRoadVehicle is simply a
limitation of C# since C# does not support multiple inheritance of
implementation. IRoadVehicle is simply a syntax construct for languages
that
support single inheritance of implementation and multiple inheritance of
pure
virtual classes (interfaces). An AmphibiousVehicle certainly is a road
vehicle
and is certainly a water vehicle. Both are specializations of vehicle
and there
is no reason why a vehicle cannot inherit or display characteristics of
both. A
modern canon can be fired and loaded, but not loaded and fired at the
same
time (hopefully). Inheritance can add behaviour. There is no reason why
a
person cannot inherit from eater and talker and not be able to eat and
talk at
the same time... although some of my friends _are_ able to do this.

Any discussion of the most basic concepts of OOP should be valid across
languages. If you truly feel that IRoadVehicle and RoadVehicle are
functionally
different then please show the code in C++ that demonstrates a
significant
functional difference other than the fact that IRoadVehicle has no
implementation.

So to summarize my argument. Interfaces and inheritance both represent
IS_A
relationships. Interfaces are a syntax construct that represents a
subset of
IS_A relationships, the pure virtual class. Containment represents HAS_A
relationships. MULTIPLE INHERITANCE represents LIKE_A relationships. So
IS_A and LIKE_A are not mutually exclusive concepts.

In C++ there is no distinction between multiple inheritance of
implementation and multiple inheritance of pure virtual classes. If you
have a
class that can be shared across classes, a so called mix in class, then
it
represents a LIKE_A relationship. Such a class can have implementation
details in C++. So in C++ a class with implementation details or a class
without implementation details can represent a LIKE_A relationship. So
in
C++ any non final class can represent a LIKE_A relationship. In C# only
pure
virtual classes can be inherited in this manner, so in _C#_ only
interfaces can
represent a LIKE_A relationship. Interfaces and base classes in C#
represent
IS_A relationships. Interfaces in C# can also represent LIKE_A
relationship.
Base classes in C# cannot represent a LIKE_A relationship. In C++ there
is no
need to distinguish between base classes and interfaces (pure virtual
classes)
since C++ supports multiple inheritance of implementation.

Regards,
Jeff
class AmphibiousVehicle : Vehicle, IRoadVehicle, IWaterVehicle

....is more accurate than saying

class AmphibiousVehicle : RoadVehicle, WaterVehicle
*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #12

P: n/a
To be clear. I am saying:

class AmphibiousVehicle : Vehicle, IRoadVehicle, IWaterVehicle

....can be expressed in C++ as

class AmphibiousVehicle : Vehicle, RoadVehicle, WaterVehicle

Where Vehicle, RoadVehicle and WaterVehicle all represent IS_A
relationsips. I
agree about the class design.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #13

P: n/a
On Wed, 04 May 2005 17:27:21 -0400, John Salerno
<jo******@NOSPAMgmail.com> wrote:
Hi all. I have a question about interfaces now. According to the book
I'm reading, when you implement an interface, the class or structure
has to declare all the methods that the interface includes.

My question is, if you must declare each method (as opposed to simply
'using' those methods like an #included file), then why not just
declare the methods on your own as if you created them yourself? What
advantage does using an interface have if you must manually declare
all the methods anyway?

Thanks.


John,

Reading through the answers I am missing a few obvious things and also
disadvantages of using interfaces versus (partly implemented) base
classes.

What you do in Interface that you dont do in an abstract base class ?
You are totally implementation independent. That means if you have to
support massively different implementations( like OS-s, Frameworks,
third party components for instance) you win something for the
clients: uniformity. Clients dont have to know about the
implementation details. For good examples you should look up both
Adapter and Bridge Pattern Examples. Also for theorem look up
ADT(Abstract Data Type).

What do you lose when you implement and Interface ? Reusability of the
implementation( obviously). When you implement base class 80% logical
implementation and maybe use 20% Template method to allow subclasses
to differ then you can really gain in development time on new
subclasses. Most application designs have some kind of challenge like
this hidden in it.

Ofcourse there is also the possibility to implement BOTH but most of
the times I think the forces ask mainly for (partially abstract) base
classes at the right abstraction level. Only when you design multi
framework, multi os kind of thing or designing a framework or os
yourself using interfaces might be a good choice imho, also because
the clients then can relate to the smaller footprint Interface and
lazy load the adequat implementation if they want too.
Rick




Nov 17 '05 #14

This discussion thread is closed

Replies have been disabled for this discussion.