interface question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • John Salerno

    #1

    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.
  • Bruce Wood

    #2
    Re: interface question

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

    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.)

    Comment

    • Robbe Morris [C# MVP]

      #3
      Re: interface question

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



      --
      2004 and 2005 Microsoft MVP C#
      Robbe Morris





      "John Salerno" <johnjsal@NOSPA Mgmail.com> wrote in message
      news:ENGdnYKWy7 qgo-TfRVn-pw@rcn.net...[color=blue]
      > 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.[/color]


      Comment

      • clintonG

        #4
        Re: interface question

        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" <brucewood@cana da.com> wrote in message
        news:1115242901 .127760.68980@f 14g2000cwb.goog legroups.com...[color=blue]
        > My question is, if you must declare each method (as opposed to simply[/color]
        [color=blue]
        > 'using' those methods like an #included file), then why not just
        > declare the methods on your own as if you created them yourself? What[/color]
        [color=blue]
        > advantage does using an interface have if you must manually declare
        > all the methods anyway?[/color]

        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.)


        Comment

        • Jeff Louie

          #5
          Re: interface question

          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 ***

          Comment

          • Bruce Wood

            #6
            Re: interface question

            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.

            Comment

            • Bruce Wood

              #7
              Re: interface question

              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.

              Comment

              • ABC

                #8
                Re: interface question

                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.


                Comment

                • clintonG

                  #9
                  Re: interface question

                  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" <brucewood@cana da.com> wrote in message
                  news:1115272774 .227271.95350@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.


                  Comment

                  • Jeff Louie

                    #10
                    Re: interface question

                    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 ***

                    Comment

                    • Joanna Carter \(TeamB\)

                      #11
                      Re: interface question

                      "Jeff Louie" <anonymous@devd ex.com> a écrit dans le message de news:
                      O$4RjhdUFHA.212 4@TK2MSFTNGP14. phx.gbl...
                      [color=blue]
                      > 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++.[/color]

                      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 AmphibiousVehic le : Vehicle, IRoadVehicle, IWaterVehicle

                      ....is more accurate than saying

                      class AmphibiousVehic le : RoadVehicle, WaterVehicle

                      Joanna

                      --
                      Joanna Carter
                      Consultant Software Engineer


                      Comment

                      • Jeff Louie

                        #12
                        Re: interface question

                        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 AmphibiousVehic le 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 AmphibiousVehic le : Vehicle, IRoadVehicle, IWaterVehicle

                        ....is more accurate than saying

                        class AmphibiousVehic le : RoadVehicle, WaterVehicle


                        *** Sent via Developersdex http://www.developersdex.com ***

                        Comment

                        • Jeff Louie

                          #13
                          Re: interface question

                          To be clear. I am saying:

                          class AmphibiousVehic le : Vehicle, IRoadVehicle, IWaterVehicle

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

                          class AmphibiousVehic le : 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 ***

                          Comment

                          • Rick Elbers

                            #14
                            Re: interface question

                            On Wed, 04 May 2005 17:27:21 -0400, John Salerno
                            <johnjsal@NOSPA Mgmail.com> wrote:
                            [color=blue]
                            >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.[/color]

                            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










                            Comment

                            Working...