what's the difference between inheritance and polymorphism?

前端 未结 8 1754
[愿得一人]
[愿得一人] 2020-12-05 05:08

can you give me a simple example of inheritance and polymorphism, so it could be fully clear and understandable?

using C# would make it more clear, as I already lear

相关标签:
8条回答
  • 2020-12-05 05:48

    This is polymorphism:

    public interface Animal 
    {
      string Name { get; }
    }
    
    public class Dog : Animal
    {
      public string Name { get { return "Dog"; } }
    }
    
    public class Cat : Animal
    {
      public string Name { get { return "Cat"; } }
    }
    
    public class Test 
    {
      static void Main()
      {
          // Polymorphism
          Animal animal = new Dog();
    
          Animal animalTwo = new Cat();
    
          Console.WriteLine(animal.Name);
          Console.WriteLine(animalTwo.Name);
      }
    }
    

    this is Inheritance:

    public class BaseClass
        {
            public string HelloMessage = "Hello, World!";
        }
    
        public class SubClass : BaseClass
        {
            public string ArbitraryMessage = "Uh, Hi!";
        }
    
        public class Test
        {
            static void Main()
            {
                SubClass subClass = new SubClass();
    
                // Inheritence
                Console.WriteLine(subClass.HelloMessage);
            }
        }
    
    0 讨论(0)
  • 2020-12-05 05:48

    It's all about behaviours.

    A class declares a certain behaviour (interface or contract):

    That class may also define that behaviour (implementation) or delegate either the whole or part of it to any of its subclasses:

    In pseudocode:

    class Animal {
        method walk()
        method speak()
        method jump()
        // ... here goes the implementation of the methods
    }
    

    Through subclassing you make a class inherit another class' behaviour.

    When the implementation of a method is delegated to subclasses, the method is called abstract in the base class and, in languages like Java, the whole base class becomes abstract as well:

    abstract class Animal {
        method walk() {
           doWalk()
        }
        method speak() {
           print "hi, I am an animal!"
        }
        abstract method jump() // delegated to specific animals
    }
    
    class Horse inherits from Animal {
        override method walk() {
            doWalkLikeAHorse()
        }
        override method speak() {
            print "hi, I am a horse!"
        }
        override method jump() { 
            doJumpLikeAHorse()
        }
    }
    
    class Elephant inherits from Animal {
        override method walk() {
            doWalkLikeAnElephant()
        }
        override method speak() {
            print "hi, I am an elephant!"
        }
        override method jump() { 
            throw error "Sorry, I can't jump!!"
        } 
    }
    

    A class' behaviour is by default virtual, which means that any class methods may be overridden by any subclasses. This is how it works in languages like C# and Java, but not necessarily in C++, for example.

    In substance, the behaviour of a base class is only virtual and may assume "multiple" (poly) "different forms" (morphs) when subclasses override that virtual behaviour. That's why it's called polymorphism. In pseudocode:

    function makeAnimalSpeak(Animal animal) {
        animal.speak();
    }
    
    makeAnimalSpeak(new Elephant()) // output: "hi, I am an elephant"
    makeAnimalSpeak(new Horse())  // output: "hi, I am a horse"
    

    Other people have offered you better examples here.

    In languages like C# and Java you have the idea of interface (which does not exist in C++), which is just a declaration of a behaviour. An interface, unlike a class, has no obligation to implement a behaviour. It's just a declaration. Any class may implement that behaviour, no matter what base class they inherit from. In pseudocode:

    interface FlyingBeing {
        method fly()
    }
    
    class FlyingPig inherits from Animal implements FlyingBeing {
        method fly() {
           print "hey, look at me, I am a flying pig!!"
        }
    }
    
    0 讨论(0)
  • 2020-12-05 05:55

    Polymorphism is the act of overriding what you Inherited.

    If you don't override it, it's not polymorphism, it's just inheritance.

    0 讨论(0)
  • 2020-12-05 05:55

    When you derive a class from a base class, the derived class will inherit all members of the base class except constructors, though whether the derived class would be able to access those members would depend upon the accessibility of those members in the base class. C# gives us polymorphism through inheritance. Inheritance-based polymorphism allows us to define methods in a base class and override them with derived class implementations. Thus if you have a base class object that might be holding one of several derived class objects, polymorphism when properly used allows you to call a method that will work differently according to the type of derived class the object belongs to.

    Reference: http://www.codeproject.com/Articles/1445/Introduction-to-inheritance-polymorphism-in-C

    0 讨论(0)
  • 2020-12-05 05:59

    Let's explain this in a more interesting way. Inheritance is the way derived class make use of the functionality of base class. Polymorphism is the way base class make use of implementation of the derived class.

    public class Triangle :Shape {
     public int getSides() {
      return 3;
     }
    }
    
    }
    public class Shape {
     public boolean isSharp(){
      return true;
     }
     public virtual int getSides(){
      return 0 ;
     }
    
     public static void main() {
      Triangle tri = new Triangle();
      System.Console.WriteLine("Triangle is a type of sharp? " + tri.isSharp());  //Inheritance 
      Shape shape = new Triangle();
      System.Console.WriteLine("My shape has " + shape.getSides() + " sides.");   //Polymorphism 
     }
    }
    
    0 讨论(0)
  • 2020-12-05 06:03

    Let's use my favorite verb and we find:

    http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29

    http://msdn.microsoft.com/en-us/library/ms173152%28v=vs.80%29.aspx

    Polymorphism and Inheritance are pivotal, need-to-be-ingrained and fundamental concepts to C# and object oriented programming. saying you know C# and not this is like knowing how to speak English and have no concept of what the alphabet is. Sorry to be blunt, but it is true.

    From the Wiki link above (this is not mine), here is an example of Polymorphism (converted to C#...)

    public class Animal
    {
        public virtual String talk() { return "Hi"; }
        public string sing() { return "lalala"; }
    }
    
    public class Cat : Animal
    {
        public override String talk() { return "Meow!"; }
    }
    
    public class Dog : Animal
    {
        public override String  talk() { return "Woof!"; }
        public new string sing() { return "woofa woofa woooof"; }
    }
    
    public class CSharpExampleTestBecauseYouAskedForIt
    {
        public CSharpExampleTestBecauseYouAskedForIt()
        {
            write(new Cat());
            write(new Dog());
        }
    
        public void write(Animal a) {
            System.Diagnostics.Debug.WriteLine(a.talk());
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题