What is polymorphism?

SBS21332108

New member
Joined
Mar 8, 2014
Messages
1
Programming Experience
Beginner
Hi C# programmers, I need help, can anyone please explain to me what is polymorphism and how it's related to C#. Thanks:concern:
 
What do you not understand about it from what you've already read? There's plenty of information out there already so there's no point our repeating what you've already read if you don't understand that?
 
I am new to C# and wanted to ask few questions about Polymorphism so I thought I would continue on from this thread.
I have read up on polymorphism.

Let's say I have a parent class called Animal and a child class called Dog. Dog inherits Animal. So like this:

C#:
using System;
namespace Polymorphism
{
    class Animal
    {
        public string FirstName = "FN";
        public string LastName = "LN";
        
        public void [COLOR=#0000ff]DisplayFullName[/COLOR]()
        {
            Console.WriteLine(FirstName + " " + LastName);
        }
    }

    class Dog : Animal
    {
        public void [COLOR=#0000ff]DisplayFullName[/COLOR]()
        {
            Console.WriteLine(FirstName + " " + LastName + " - [COLOR=#ff0000]Woof[/COLOR]");
        }
    }

    class Program
    {
        static void Main()
        {
            Animal a = new Dog();
            a.DisplayFullName();
        }
    }
}


Now from what I understand, Polymorphism allows you to declare a Parent class reference variable that is able to point to a Child class object i.e. Animal a = new Dog().
I am also aware that during run time, the variable changes it's type i.e. the variable a changes from Animal to Dog or does it change from Dog to Animal? I am not too sure.
I am also convinced that this (i.e. at run time data changes) only if we use the keywords "virtual" (in the parent class method called DisplayFullName()) and "override" (in the child class method called DisplayFullName()). I have purposely left these keywords out in my code above so that it invokes the Parent class method and not the child class method. Does that mean that during that particular run time, no implicit data conversion happened for the variable a? And if so, does that mean a remained as an Animal type throughout?

Now, things change when I used the keywords "virtual" and "override". Lets imagine I add these words into my code above. Now, does this cause the variable a to change t data type during run time? If so, am I correct in saying "during runtime, variable a changes from an Animal type to a Dog type?
 
I am also aware that during run time, the variable changes it's type i.e. the variable a changes from Animal to Dog or does it change from Dog to Animal? I am not too sure.

You are not aware of that because that never happens. Nothing changes type. The variable 'a' is declared as type Animal and it is always that type. The variable is type Animal and it refers to an object of type Dog. That's it, that's all. Polymorphism seems complicated because people think of it in the abstract but, like so much of OOP, it works just like the real world. Consider a vet hospital. It accepts animals of all types. You can think of each appointment at the hospital as having a variable of type Animal. You can assign a dog to that variable, or a cat, or a snake or anything else that is an animal. That exactly how it works in programming. You declare a variable of a particular type and you can then assign any object of that type to the variable, regardless of what other more specific type(s) that object may be.

Consider a form in a Windows Forms app. It has an ActiveControl property that is type Control and it refers to the control on the form that currently has focus. That control might be a TextBox, a Button, A ListBox or any other type of control that can receive focus. Based on the ActiveControl property, all you know is that it is a control, so you can only access members of the Control class via that property. If you want to access members of a more specific type then you must cast as that type.
 
With regards to the use of the 'virtual' and 'overrides' keywords, when a derived class declares a method with the same name and signature as a method in the base class, the derived implementation can either hide or override the base implementation. Hiding is referred to as shadowing in VB. When you override a method, you are replacing the base implementation with the derived implementation. When you hide a method, the base implementation is still there but not seen from the derived type. A call to an overridden method follows the type of the object while a call to a hidden method follows the type of the reference (the variable). See this example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            BaseClass bc1 = new BaseClass();

            bc1.OverriddenMethod();
            bc1.HiddenMethod();

            DerivedClass dc = new DerivedClass();

            dc.OverriddenMethod();
            dc.HiddenMethod();

            BaseClass bc2 = new DerivedClass();

            bc2.OverriddenMethod();
            bc2.HiddenMethod();

            Console.ReadLine();
        }
    }

    public class BaseClass
    {
        public virtual void OverriddenMethod()
        {
            Console.WriteLine("BaseClass.OverriddenMethod");
        }

        public void HiddenMethod()
        {
            Console.WriteLine("BaseClass.HiddenMethod");
        }
    }

    public class DerivedClass : BaseClass
    {
        public override void OverriddenMethod()
        {
            Console.WriteLine("DerivedClass.OverriddenMethod");
        }

        public new void HiddenMethod()
        {
            Console.WriteLine("DerivedClass.HiddenMethod");
        }
    }
}

If you execute that code then you'll see that the first two lines call methods of the base class and the next two lines call methods of the derived class, as you would expect. For the last two lines, you have a reference of type BaseClass that refers to an object of type DerivedClass. When you call an overridden method on that, you get the derived implementation, i.e. it follows the type of the object. When you call a hidden method on that, you get the base implementation, i.e. it follows the type of the reference.

Also note that, while you don't have to, you ought to use the 'new' keyword when hiding a base member, as I have in this example.
 
quote from elsewhere
Theword polymorphism means having many forms. Inobject-oriented programming paradigm, polymorphism is often expressedas 'one interface, multiple functions'.
Polymorphism can be static or dynamic.In static polymorphism, the response to a function is determinedat the compile time. In dynamic polymorphism, it is decided atrun-time.
[h=2]Static Polymorphism[/h]The mechanism of linking a functionwith an object during compile time is called early binding. It isalso called static binding. C# provides two techniques to implementstatic polymorphism. They are ?

  • Function overloading
  • Operator overloading
[h=2]DynamicPolymorphism[/h]C# allows you to create abstractclasses that are used to provide partial class implementation of aninterface. Implementation is completed when a derived class inheritsfrom it. Abstract classes contain abstract methods, whichare implemented by the derived class. The derived classes have morespecialized functionality.
Here are the rules about abstractclasses ?

  • You cannot create an instance of an abstract class
  • You cannot declare an abstract method outside an abstract class
  • When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.
 
Polymorphism is to get methods and instances in object reused. If object is the main function instead of reinvite wheel you use same wheel but give it new updates/features.

This is the sole purpose of object oriented programming. Just look up "object oriented programming" and you will get it. Only by looking on the code you get a look at the soul but not description of the soul

Polymorphism means "many shapes" from Greek, just like you have a head so does the horse but does the same thing, eating, seeing hearing.

Think of da vinci, a human in a circle makes many shapes
 
Last edited:
Back
Top Bottom