Difference between revisions of "Polymorphism"
From Logic Wiki
| (3 intermediate revisions by the same user not shown) | |||
| Line 13: | Line 13: | ||
in child class | in child class | ||
| − | public <b style="color:red;">override</b> void Gazla(int | + | public <b style="color:red;">override</b> void Gazla(int ivme) |
{ | { | ||
// base.Gazla // to use base method as it is | // base.Gazla // to use base method as it is | ||
| Line 75: | Line 75: | ||
} | } | ||
</pre> | </pre> | ||
| + | ----------------------------------- | ||
| + | |||
| + | |||
| + | Related Subjects : [[Abstract]], [[interface]], [[Sealed Modifier]] | ||
Latest revision as of 10:19, 26 February 2026
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