473,881 Members | 1,687 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

interface question

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
13 3275
> 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 "polymorphi sm": 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(IGreet ing person)
{
Console.WriteLi ne(person.Hello );
person.ShakeHan ds();
}

"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
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******@NOSPA Mgmail.com> wrote in message
news:EN******** ************@rc n.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
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*******@cana da.com> wrote in message
news:11******** *************@f 14g2000cwb.goog legroups.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 "polymorphi sm": 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(IGreet ing person)
{
Console.WriteLi ne(person.Hello );
person.ShakeHan ds();
}

"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
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
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(mortim er);

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 "polymorphi sm": 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 "polymorphi c":
"different shapes"), so long as their classes implement the required
interface.

Nov 17 '05 #6
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
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
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*******@cana da.com> wrote in message
news:11******** *************@g 14g2000cwa.goog legroups.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(mortim er);

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 "polymorphi sm": 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 "polymorphi c":
"different shapes"), so long as their classes implement the required
interface.
Nov 17 '05 #9
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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

65
5411
by: perseus | last post by:
I think that everyone who told me that my question is irrelevant, in particular Mr. David White, is being absolutely ridiculous. Obviously, most of you up here behave like the owners of the C++ language. A C++ interface installation IS ABOUT THE C++ LANGUAGE! The language does not possess the ability to handle even simple file directory manipulation. Those wise people that created it did not take care of it. So, BOOST is a portable...
26
2117
by: Marius Horak | last post by:
As in subject. Thanks MH
4
8586
by: jm | last post by:
Consider: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon/html/vbconwhenshouldiimplementinterfacesinmycomponent.asp // Code for the IAccount interface module. public interface IAccount { void PostInterest(); void DeductFees(IFeeSchedule feeSchedule); }
20
4270
by: Ole Hanson | last post by:
I am accessing my database through an interface, to allow future substitution of the physical datastore - hence I would like to declare in my Interface that my DAL-objects implementing the interface and accessing the datastore MUST pass in a UserToken in the constructor of the object. Is this not possible? Am I forced to add the UserToken as a property on the object instead? /Ole
6
6086
by: John Salerno | last post by:
I understand how they work (basically), but I think maybe the examples I'm reading are too elementary to really show their value. Here's one from Programming C#: #region Using directives using System; using System.Collections.Generic; using System.Text;
10
667
by: Joe | last post by:
My question is more an OOD question. I know *how* to implement both abstract classes and interfaces. Here's my question - under what circumstacnes does one use an abstract class and under what circumstacnes does one implement an interface? TIA, -- Joe VBA Automation/VB/C++/Web and DB development
4
2864
by: Ray Dukes | last post by:
What I am looking to do is map the implementation of interface properties and functions to an inherited method of the base class. Please see below. '**************************************************************************** ' Issues '****************************************************************************
5
1675
by: Colin McGuire | last post by:
Hi all, when I write the class below Private Class employee End Class and then add the line "Implements IVF" which is an interface I have written, the IDE modifies my code to display
52
20931
by: Ben Voigt [C++ MVP] | last post by:
I get C:\Programming\LTM\devtools\UselessJunkForDissassembly\Class1.cs(360,27): error CS0535: 'UselessJunkForDissassembly.InvocableInternals' does not implement interface member 'UselessJunkForDissassembly.IInvocableInternals.OperationValidate(string)' C:\Programming\LTM\devtools\UselessJunkForDissassembly\Class1.cs(360,27): error CS0535: 'UselessJunkForDissassembly.InvocableInternals' does not implement interface member...
0
11095
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10716
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10812
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10399
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9552
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7952
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7108
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4597
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3223
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.