Interface question

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

    #1

    Interface question

    I am trying to understand Interfaces and why I would use them.

    I have an example from a book that is explaining it.

    I just can't seem to see why I would use it.

    In my example, it has 2 interfaces: IDisplayable and IComparable
    (Predefined).

    In the Students class part, he is moving the students array to an
    IComparable Object array and then sorting it.

    // utilize the IComparable interface to sort the
    // array
    IComparable[] comparableObjec ts = (IComparable[])students;
    Array.Sort(comp arableObjects);

    And then it moves the student array into the new IDisplayable interface:

    // now the IDisplayable interface to display the results
    IDisplayable[] displayableObje cts = (IDisplayable[])students;
    DisplayArray(di splayableObject s);

    And as is shown in the Birds section, I just do:

    Array.Sort(stud ents);
    DisplayArray(st udents);

    I get the same results.

    And if I have to implement all the functions described in the Interface,
    what am I really inheriting?

    Why not just use an abstract class to do this?

    Just a little confused.

    Thanks,

    Tom


  • Nicholas Paldino [.NET/C# MVP]

    #2
    Re: Interface question

    Tom,

    You aren't inheriting anything. Interfaces provide the contract, while
    an abstract class provides a contract (through abstract/virtual methods) and
    possibly an implementation.

    Interfaces are better used in situations where there isn't a clear
    default implementation (in this case, the IComparable interface). It is
    also better to use interfaces in general because you might not have the
    opportunity to define the base class on your class (due to the fact that you
    can only inherit from one base class).


    --
    - Nicholas Paldino [.NET/C# MVP]
    - mvp@spam.guard. caspershouse.co m

    "tshad" <tfs@dslextreme .comwrote in message
    news:OAQNbVGBIH A.4836@TK2MSFTN GP06.phx.gbl...
    >I am trying to understand Interfaces and why I would use them.
    >
    I have an example from a book that is explaining it.
    >
    I just can't seem to see why I would use it.
    >
    In my example, it has 2 interfaces: IDisplayable and IComparable
    (Predefined).
    >
    In the Students class part, he is moving the students array to an
    IComparable Object array and then sorting it.
    >
    // utilize the IComparable interface to sort the
    // array
    IComparable[] comparableObjec ts = (IComparable[])students;
    Array.Sort(comp arableObjects);
    >
    And then it moves the student array into the new IDisplayable interface:
    >
    // now the IDisplayable interface to display the results
    IDisplayable[] displayableObje cts = (IDisplayable[])students;
    DisplayArray(di splayableObject s);
    >
    And as is shown in the Birds section, I just do:
    >
    Array.Sort(stud ents);
    DisplayArray(st udents);
    >
    I get the same results.
    >
    And if I have to implement all the functions described in the Interface,
    what am I really inheriting?
    >
    Why not just use an abstract class to do this?
    >
    Just a little confused.
    >
    Thanks,
    >
    Tom
    >

    Comment

    • teel

      #3
      Re: Interface question

      On 1 Pa , 21:58, "tshad" <t...@dslextrem e.comwrote:
      I am trying to understand Interfaces and why I would use them.
      I once used interfaces in C# and understood them - I've seen a huge
      power they had, but now I forgot what power it was :)
      I remember the situation when I used them: just had an object of class
      (let's say Ford) derived some levels deep but operated it virtually,
      like Vehicle. Ford implemented some interface (e.g ICrappyModel :))))
      so I actually was assured it implements specific methods or properties
      which the more generic class (lets say nor Car neither Vehicle)
      didn't. And I had a Vehicle veh variable and wanted to know whether I
      can run a Ford-specific method, so I used:
      if (veh is ICrappyModel) { (ICrappyModel). GoToScrap() }

      I hope this helped :)

      Best regards,
      teel

      Comment

      • sloan

        #4
        Re: Interface question


        Here is a little "Hopefully, the light will go off" example.
        http://sholliday.space s.live.com/Blog/cns!A68482B9628 A842A!126.entry

        This is not directly related to your example below.

        But the premise is the same.

        I can make my routines more flexible, by having interfaces as the
        parameters. Thus I don't hard code to any one concrete class
        implementation.


        //Why not just use an abstract class to do this?//

        Maybe you can. However, you can only inherit from ONE abstract class (no
        multiple class inheritance).
        You can implement N number of interfaces. (zero, one, two, ten,
        nine-hundred).


        If you are new to OO and probably Design Patterns, I suggest:
        C# Design Patterns are proven solutions to common software design problems. Design Patterns help you write code that is more flexible, adaptable, and easier to maintain. Examples come with 100% source code.

        and the Head First Design Patterns book.


        You may need to post a working sample, because you're asking the group to
        evaluate...your evaluation... of another person's code.
        So its hard to see what he is doing.




        "tshad" <tfs@dslextreme .comwrote in message
        news:OAQNbVGBIH A.4836@TK2MSFTN GP06.phx.gbl...
        >I am trying to understand Interfaces and why I would use them.
        >
        I have an example from a book that is explaining it.
        >
        I just can't seem to see why I would use it.
        >
        In my example, it has 2 interfaces: IDisplayable and IComparable
        (Predefined).
        >
        In the Students class part, he is moving the students array to an
        IComparable Object array and then sorting it.
        >
        // utilize the IComparable interface to sort the
        // array
        IComparable[] comparableObjec ts = (IComparable[])students;
        Array.Sort(comp arableObjects);
        >
        And then it moves the student array into the new IDisplayable interface:
        >
        // now the IDisplayable interface to display the results
        IDisplayable[] displayableObje cts = (IDisplayable[])students;
        DisplayArray(di splayableObject s);
        >
        And as is shown in the Birds section, I just do:
        >
        Array.Sort(stud ents);
        DisplayArray(st udents);
        >
        I get the same results.
        >
        And if I have to implement all the functions described in the Interface,
        what am I really inheriting?
        >
        Why not just use an abstract class to do this?
        >
        Just a little confused.
        >
        Thanks,
        >
        Tom
        >

        Comment

        • James Jardine

          #5
          Re: Interface question

          tshad wrote:
          I am trying to understand Interfaces and why I would use them.
          >
          I have an example from a book that is explaining it.
          >
          I just can't seem to see why I would use it.
          >
          In my example, it has 2 interfaces: IDisplayable and IComparable
          (Predefined).
          >
          In the Students class part, he is moving the students array to an
          IComparable Object array and then sorting it.
          >
          // utilize the IComparable interface to sort the
          // array
          IComparable[] comparableObjec ts = (IComparable[])students;
          Array.Sort(comp arableObjects);
          >
          And then it moves the student array into the new IDisplayable interface:
          >
          // now the IDisplayable interface to display the results
          IDisplayable[] displayableObje cts = (IDisplayable[])students;
          DisplayArray(di splayableObject s);
          >
          And as is shown in the Birds section, I just do:
          >
          Array.Sort(stud ents);
          DisplayArray(st udents);
          >
          I get the same results.
          >
          And if I have to implement all the functions described in the Interface,
          what am I really inheriting?
          >
          Why not just use an abstract class to do this?
          >
          Just a little confused.
          >
          Thanks,
          >
          Tom
          >
          >
          I think a lot of people have difficulty understanding Interfaces and
          Abstract classes at first. I find that I rarely use an abstract class
          and more often use Interfaces because of some of the constraints
          regarding inheritance vs. implements. A good example of the use of an
          interface is for an application that allows add-ins or plug-ins to it.
          Outlook for example uses an Interface that all Add-ins must implement.
          This allows Outlook to talk to each add-in but allow each add-in to
          function its own way.

          Comment

          • tshad

            #6
            Re: Interface question

            I think a lot of people have difficulty understanding Interfaces and
            Abstract classes at first. I find that I rarely use an abstract class
            and more often use Interfaces because of some of the constraints regarding
            inheritance vs. implements. A good example of the use of an interface is
            for an application that allows add-ins or plug-ins to it. Outlook for
            example uses an Interface that all Add-ins must implement. This allows
            Outlook to talk to each add-in but allow each add-in to function its own
            way.
            But if I have an abstract such as:

            abstract class Drawable
            {
            public abstract String DrawYourself();
            }

            Is this really the same as:

            interface IDrawable
            {
            String DrawYourself();
            }

            The only difference I see here (other than the keyword differences) is the
            fact that you can only inherit 1 abstract class and can implement multiple
            interfaces.

            In both cases, I have to implement all the methods, correct?

            In this test program, I get an error because I didn't implement the
            DrawYourself method in the Circle class. I had thought that in the
            Interface you had to implement ALL the methods but that wasn't the case in
            the Abstract Classes (obviously I was wrong).

            *************** *************** *************** ****
            using System;

            namespace TestBed
            {
            abstract class Drawable
            {
            public abstract String DrawYourself();
            }

            class Circle : Drawable
            {
            }
            class Square : Drawable
            {
            public override string DrawYourself()
            {
            return "This is the Square";
            }
            }

            /// <summary>
            /// Summary description for Class1.
            /// </summary>
            class Class1
            {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main(string[] args)
            {
            //
            // TODO: Add code to start application here
            //
            Circle theCircle = new Circle();
            Console.WriteLi ne("At the Circle display = " + theCircle.DrawY ourself());
            Square theSquare = new Square();
            String theString;
            theString = theSquare.DrawY ourself();
            Console.WriteLi ne("At the Square display = " + theString);
            Console.Read();
            }
            }
            }
            *************** *************** *************** ****

            Thanks,

            Tom


            Comment

            • Peter Duniho

              #7
              Re: Interface question

              tshad wrote:
              But if I have an abstract such as:
              >
              abstract class Drawable
              {
              public abstract String DrawYourself();
              }
              >
              Is this really the same as:
              >
              interface IDrawable
              {
              String DrawYourself();
              }
              Define "the same". Obviously, it's not strictly the same. But yes, in
              that very basic example, the net effect is essentially the same.
              The only difference I see here (other than the keyword differences) is the
              fact that you can only inherit 1 abstract class and can implement multiple
              interfaces.
              >
              In both cases, I have to implement all the methods, correct?
              All methods have to implemented somewhere, yes. The difference is where
              they must be implemented.

              An abstract class can implement some methods and leave others as
              abstract. An abstract class might not implement any methods, and in
              that case it's basically the same as an interface (except that only one
              class can be inherited of course).

              An interface cannot implement any methods. It is strictly a contract
              declaration and all methods must be implemented by the class that
              declares that it's using (implementing) the interface.

              You do have to implement every method and property that's declared,
              somewhere. Whether using an abstract class or an interface, you're not
              allowed to leave something unimplemented. But an abstract class
              provides the opportunity to provide some base or default implementation,
              even while some other things have to be implemented by inheritors.

              Pete

              Comment

              • Michael S

                #8
                Re: Interface question

                tshad,

                I also don't like the IAnimal interface.

                A simple rule of thumb should be that a class defines what a object IS,
                while an interface defines what a object CAN DO.

                So, in the example you provided, IAnimal should be rename ISoundable, with
                the method .MakeSound(). Now the interface can be used for animals, cars,
                buttons, instruments and whatever that can make a sound. They all may sound
                differently, but they all make a sound.

                Interfaces should be general, like IDisposable, IClonable, IDisplayable.

                Classes are vertical, interfaces are horizontal.

                - Michael Starberg


                Comment

                Working...