Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Inheritance/Polymorphism [modified]

Inheritance/Polymorphism [modified]

Scheduled Pinned Locked Moved C#
csharpoopquestionlearningdotnet
10 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    Sundeepan Sen
    wrote on last edited by
    #1

    Hello all, my name is Sundeepan and I am new to this board and to coding as well. To train myself and get familiar with OOP concepts using the C# language I am reading, "Microsoft .NET Framework - Application Development Foundation" book by Tony Northrup. I am finding this book very informative. I do have a question that I was not able to find an answer to by querying Google. The question is as follows: If a method requires an object as one of its parameters why should one not pass an object of a base class, instead one must pass an object of the derived class? I understand that this might be a foolish question, but I am at a very early stage of my learning, any help would be appreciated. Metaphors are equally as helpful as a technical answer. Regards Sundeepan http://sundeepinthought.blogspot.com

    modified on Friday, February 5, 2010 12:32 AM

    N P K 3 Replies Last reply
    0
    • S Sundeepan Sen

      Hello all, my name is Sundeepan and I am new to this board and to coding as well. To train myself and get familiar with OOP concepts using the C# language I am reading, "Microsoft .NET Framework - Application Development Foundation" book by Tony Northrup. I am finding this book very informative. I do have a question that I was not able to find an answer to by querying Google. The question is as follows: If a method requires an object as one of its parameters why should one not pass an object of a base class, instead one must pass an object of the derived class? I understand that this might be a foolish question, but I am at a very early stage of my learning, any help would be appreciated. Metaphors are equally as helpful as a technical answer. Regards Sundeepan http://sundeepinthought.blogspot.com

      modified on Friday, February 5, 2010 12:32 AM

      N Offline
      N Offline
      Not Active
      wrote on last edited by
      #2

      class Animal
      {
      protected void Foo(){}
      }

      class Cow : Animal
      {
      public vod Moo(){}
      }

      class Farm
      {
      public void Pet(Animal animal){}
      }

      If you pass Animal to a method then you can only access the Foo method. However, if you pass Cow, you will have access to both Moo and Foo methods since Cow derives from Animal.


      I know the language. I've read a book. - _Madmatt

      S 1 Reply Last reply
      0
      • N Not Active

        class Animal
        {
        protected void Foo(){}
        }

        class Cow : Animal
        {
        public vod Moo(){}
        }

        class Farm
        {
        public void Pet(Animal animal){}
        }

        If you pass Animal to a method then you can only access the Foo method. However, if you pass Cow, you will have access to both Moo and Foo methods since Cow derives from Animal.


        I know the language. I've read a book. - _Madmatt

        S Offline
        S Offline
        Sundeepan Sen
        wrote on last edited by
        #3

        So if I wrote

        class Farm
        {
        public void Pet(Cow chicken){}
        }

        I can access both Foo and Moo? But if I wrote

        class Farm
        {
        public void Pet(Animal man){}
        }

        then I can only access the Foo method? Lol..nice example though....clarification is needed if you don't mind :-D

        W 1 Reply Last reply
        0
        • S Sundeepan Sen

          So if I wrote

          class Farm
          {
          public void Pet(Cow chicken){}
          }

          I can access both Foo and Moo? But if I wrote

          class Farm
          {
          public void Pet(Animal man){}
          }

          then I can only access the Foo method? Lol..nice example though....clarification is needed if you don't mind :-D

          W Offline
          W Offline
          Wamuti
          wrote on last edited by
          #4

          sundeepan wrote:

          Cow chicken

          and

          sundeepan wrote:

          Animal man

          was a really comical. :laugh: Anyway i don't see any clarification to make since it is just as you say. When you inherit, you get the members you inherit and in addition any member you make in the new class. Just like if someone left you some items to travel to an unknown land (X|) then, you'd have the items you originally owned plus the ones he left you. But he would not have the items you own since you never gave it to them.

          Wamuti: Any man can be an island, but islands to need water around them! Edmund Burke: No one could make a greater mistake than he who did nothing because he could do only a little.

          1 Reply Last reply
          0
          • S Sundeepan Sen

            Hello all, my name is Sundeepan and I am new to this board and to coding as well. To train myself and get familiar with OOP concepts using the C# language I am reading, "Microsoft .NET Framework - Application Development Foundation" book by Tony Northrup. I am finding this book very informative. I do have a question that I was not able to find an answer to by querying Google. The question is as follows: If a method requires an object as one of its parameters why should one not pass an object of a base class, instead one must pass an object of the derived class? I understand that this might be a foolish question, but I am at a very early stage of my learning, any help would be appreciated. Metaphors are equally as helpful as a technical answer. Regards Sundeepan http://sundeepinthought.blogspot.com

            modified on Friday, February 5, 2010 12:32 AM

            P Offline
            P Offline
            PIEBALDconsult
            wrote on last edited by
            #5

            sundeepan wrote:

            why should one not pass an object of a base class

            Who says you shouldn't? There are many cases where you would.

            S 1 Reply Last reply
            0
            • S Sundeepan Sen

              Hello all, my name is Sundeepan and I am new to this board and to coding as well. To train myself and get familiar with OOP concepts using the C# language I am reading, "Microsoft .NET Framework - Application Development Foundation" book by Tony Northrup. I am finding this book very informative. I do have a question that I was not able to find an answer to by querying Google. The question is as follows: If a method requires an object as one of its parameters why should one not pass an object of a base class, instead one must pass an object of the derived class? I understand that this might be a foolish question, but I am at a very early stage of my learning, any help would be appreciated. Metaphors are equally as helpful as a technical answer. Regards Sundeepan http://sundeepinthought.blogspot.com

              modified on Friday, February 5, 2010 12:32 AM

              K Offline
              K Offline
              Keith Barrow
              wrote on last edited by
              #6

              I actually almost say the contrary is true. Mark Nischalke's answer holds true, you do have access to both the Moo() and Foo() methods by passing the subclass. However to do so couples the method to the subclass, and other instances of the animal class cannot be passed:

              class Program
              {
              static void MakeAnimalSpeak(Animal animal)
              {

                  animal.MakeNoise();
              }
              
              static void MakeAnimalSpeakCoupled(Cow animal)
              {
                  // This is more tighltly coupled to cow: 
                  // this method cannot be called for duck
                  animal.MakeNoise();
              }
              
              
              static void Milk(Cow animal)
              {
                  animal.Milk();
                  animal.MakeNoise(); // Cow is mooing with happiness
              }
              
              
              
              static void Main(string\[\] args)
              {
                  Cow cow = new Cow();
                  Duck duck = new Duck();
                  MakeAnimalSpeak(cow);
                  MakeAnimalSpeak(duck);
                  MakeAnimalSpeakCoupled(cow);
                  //MakeAnimalSpeakCoupled(duck); //Coupled to cow: this is a worse implementation in this context
                  Milk(cow);
                  //Milk(duck); //Can't, but not a problem. Milking a duck is nonsensical!
              }
              

              }

              abstract class Animal
              {
              public abstract void MakeNoise();
              }

              class Cow : Animal
              {
              public override void MakeNoise() { Console.WriteLine("Moo"); }
              public void Milk() { Console.Write("Sloooosh"); }
              }

              class Duck : Animal
              {
              public override void MakeNoise() { Console.WriteLine("Quack"); }
              }

              Of course it is horses for courses, as with everythign in the code world. In the example Mark gave, you should pass the cow if you need access to both Moo() and Foo() but otherwise IMO is is better to pass an Animal instead. Better yet, coding to Intefraces produces cleaner results still, and helps with testing (as mock objects can be passed more easily)

              Cpianism: I have a negative number in my Rep so please fix it. Chris Maunder: That isn't a bug.

              S 1 Reply Last reply
              0
              • P PIEBALDconsult

                sundeepan wrote:

                why should one not pass an object of a base class

                Who says you shouldn't? There are many cases where you would.

                S Offline
                S Offline
                Sundeepan Sen
                wrote on last edited by
                #7

                This is the paragraph that threw me off: "Another benefit of inheritance is the ability to use derived classes interchangeably, a concept called polymorphism. For example, there are five classes that inherit from the System.Drawing.Brush base class: HatchBrush, LinearGradientBrush, PathGradientBrush, SolidBrush, and TextureBrush. The Graphics.DrawRectangle method requires a Brush object as one of its parameters however, you never pass an object of the base Brush class to Graphics.DrawRectangle. Instead you pass an object of one of the derived classes. Because they are each derived from the Brush class, the graphics.DrawRectangle method can accept any of them. Similarly if you were to create a custom class derived from the Brush class, you could also pass an object of that class to Graphics.DrawRectangle. "

                P 1 Reply Last reply
                0
                • S Sundeepan Sen

                  This is the paragraph that threw me off: "Another benefit of inheritance is the ability to use derived classes interchangeably, a concept called polymorphism. For example, there are five classes that inherit from the System.Drawing.Brush base class: HatchBrush, LinearGradientBrush, PathGradientBrush, SolidBrush, and TextureBrush. The Graphics.DrawRectangle method requires a Brush object as one of its parameters however, you never pass an object of the base Brush class to Graphics.DrawRectangle. Instead you pass an object of one of the derived classes. Because they are each derived from the Brush class, the graphics.DrawRectangle method can accept any of them. Similarly if you were to create a custom class derived from the Brush class, you could also pass an object of that class to Graphics.DrawRectangle. "

                  P Offline
                  P Offline
                  PIEBALDconsult
                  wrote on last edited by
                  #8

                  It sounds like the author isn't a very good technical writer. Which is one of my complaints about mass-market programming books. And one of the benefits of taking a class with a real live teacher -- you can ask the teacher for clarification. That may not be a good example -- System.Drawing.Brush is abstract, so you can't have an instance of it anyway. But if you do have an instance of it, then you could go right ahead and pass it (but who knows what would happen).

                  S 1 Reply Last reply
                  0
                  • P PIEBALDconsult

                    It sounds like the author isn't a very good technical writer. Which is one of my complaints about mass-market programming books. And one of the benefits of taking a class with a real live teacher -- you can ask the teacher for clarification. That may not be a good example -- System.Drawing.Brush is abstract, so you can't have an instance of it anyway. But if you do have an instance of it, then you could go right ahead and pass it (but who knows what would happen).

                    S Offline
                    S Offline
                    Sundeepan Sen
                    wrote on last edited by
                    #9

                    Its a "Microsoft Press" book for the 70-536 cert exam...this guy better be a good technical writer lol!

                    1 Reply Last reply
                    0
                    • K Keith Barrow

                      I actually almost say the contrary is true. Mark Nischalke's answer holds true, you do have access to both the Moo() and Foo() methods by passing the subclass. However to do so couples the method to the subclass, and other instances of the animal class cannot be passed:

                      class Program
                      {
                      static void MakeAnimalSpeak(Animal animal)
                      {

                          animal.MakeNoise();
                      }
                      
                      static void MakeAnimalSpeakCoupled(Cow animal)
                      {
                          // This is more tighltly coupled to cow: 
                          // this method cannot be called for duck
                          animal.MakeNoise();
                      }
                      
                      
                      static void Milk(Cow animal)
                      {
                          animal.Milk();
                          animal.MakeNoise(); // Cow is mooing with happiness
                      }
                      
                      
                      
                      static void Main(string\[\] args)
                      {
                          Cow cow = new Cow();
                          Duck duck = new Duck();
                          MakeAnimalSpeak(cow);
                          MakeAnimalSpeak(duck);
                          MakeAnimalSpeakCoupled(cow);
                          //MakeAnimalSpeakCoupled(duck); //Coupled to cow: this is a worse implementation in this context
                          Milk(cow);
                          //Milk(duck); //Can't, but not a problem. Milking a duck is nonsensical!
                      }
                      

                      }

                      abstract class Animal
                      {
                      public abstract void MakeNoise();
                      }

                      class Cow : Animal
                      {
                      public override void MakeNoise() { Console.WriteLine("Moo"); }
                      public void Milk() { Console.Write("Sloooosh"); }
                      }

                      class Duck : Animal
                      {
                      public override void MakeNoise() { Console.WriteLine("Quack"); }
                      }

                      Of course it is horses for courses, as with everythign in the code world. In the example Mark gave, you should pass the cow if you need access to both Moo() and Foo() but otherwise IMO is is better to pass an Animal instead. Better yet, coding to Intefraces produces cleaner results still, and helps with testing (as mock objects can be passed more easily)

                      Cpianism: I have a negative number in my Rep so please fix it. Chris Maunder: That isn't a bug.

                      S Offline
                      S Offline
                      Sundeepan Sen
                      wrote on last edited by
                      #10

                      This is great, I like the humor involved too. I am saving this reply as a PDF on my computer. Thanks again!

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups