Difference between revisions of "Polymorphism"

From Logic Wiki
Jump to: navigation, search
(public int Width{get; set;})
Line 22: Line 22:
 
public class Circle : Shape
 
public class Circle : Shape
 
{
 
{
 +
  public override void Draw()
 +
  {
 +
  Console.WriteLine("Draw a circle");
 +
  }
 
}
 
}
  
 
public class Rectangle : Shape  
 
public class Rectangle : Shape  
 
{
 
{
 +
  public override void Draw()
 +
  {
 +
  Console.WriteLine("Draw a Rectangle");
 +
  }
 
}
 
}
  
 
public class Shape  
 
public class Shape  
 
{
 
{
 +
  public int Width {get; set;}
 +
  public int Height{get; set;}
 +
  public Position Position {get; set;}
  
 +
  public virtual void Draw()
 +
  {
 +
  }
 
}
 
}
 +
</pre>
 +
How we use it
 +
<pre class=brush:csharp;">
 +
public class Canvas
 +
{
 +
  public void DrawShapes(List<Shape> shapes)
 +
  {
 +
    foreach (var shape in shapes)
 +
    {
 +
    shape.Draw();
 +
    }
 +
  }
 +
}
 +
</pre>
 +
How we call it
 +
<pre class=brush:csharp;">
 +
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);
 +
  }
 +
}
 +
</pre>

Revision as of 10:07, 13 June 2017


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 icme)
{
 // 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);
  }
}