Polymorphism

From Logic Wiki
Jump to: navigation, search


if you want to use a method or property of a base class differently in child classes you need polymorphism.

Simply add virtual keyword to base class's method

public virtual void Gazla(int ivme)
{
 this.Hiz += ivme;
}

in child class

public override void Gazla(int ivme)
{
 // base.Gazla // to use base method as it is
  this.hiz += 2 * ivme;
}

public class Circle : Shape
{
  public override void Draw()
  {
   Console.WriteLine("Draw a circle");
  }
}

public class Rectangle : Shape 
{
  public override void Draw()
  {
   Console.WriteLine("Draw a Rectangle");
  }
}

public class Shape 
{
  public int Width {get; set;}
  public int Height{get; set;}
  public Position Position {get; set;}

  public virtual void Draw()
  {
  }
}

How we use it

public class Canvas
{
  public void DrawShapes(List<Shape> shapes)
  {
    foreach (var shape in shapes)
    {
     shape.Draw();
    }
  }
}

How we call it

class Program
{
  static void Main(string[] args)
  {
    var shapes = new List<Shape>();
    shapes.Add(new Circle{Width:100, Height:100,...}); 
    shapes.Add(new Rectangle{Width:100, Height:100,...});

    var Canvas = new Canvas();
    canvas.DrawShapes(shapes);
  }
}


Related Subjects : Abstract, interface, Sealed Modifier