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:
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();
}
}
}
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.
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"); } } }
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 ?
[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.
- Function overloading
- Operator overloading
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.