Inheritance and Polymorphism
Polymorphic Arrays
A base-class array can hold different derived objects and call virtual methods.
Polymorphic Arrays
PolymorphicArrays.cs
using System;
class Shape
{
public virtual string Name()
{
return "shape";
}
}
class Circle : Shape
{
public override string Name()
{
return "circle";
}
}
class Square : Shape
{
public override string Name()
{
return "square";
}
}
class Program
{
static void Main()
{
string separator = ;
Shape[] shapes = { new Circle(), new Square() };
string summary = "";
foreach (Shape shape in shapes)
{
if (summary.Length > 0)
{
summary += separator;
}
summary += shape.Name();
}
Console.WriteLine($"separator={separator}");
Console.WriteLine($"summary={summary}");
}
}
using System;
class Shape
{
public virtual string Name()
{
return "shape";
}
}
class Circle : Shape
{
public override string Name()
{
return "circle";
}
}
class Square : Shape
{
public override string Name()
{
return "square";
}
}
class Program
{
static void Main()
{
string separator = ;
Shape[] shapes = { new Circle(), new Square() };
string summary = "";
foreach (Shape shape in shapes)
{
if (summary.Length > 0)
{
summary += separator;
}
summary += shape.Name();
}
Console.WriteLine($"separator={separator}");
Console.WriteLine($"summary={summary}");
}
}
using System;
class Shape
{
public virtual string Name()
{
return "shape";
}
}
class Circle : Shape
{
public override string Name()
{
return "circle";
}
}
class Square : Shape
{
public override string Name()
{
return "square";
}
}
class Program
{
static void Main()
{
string separator = ;
Shape[] shapes = { new Circle(), new Square() };
string summary = "";
foreach (Shape shape in shapes)
{
if (summary.Length > 0)
{
summary += separator;
}
summary += shape.Name();
}
Console.WriteLine($"separator={separator}");
Console.WriteLine($"summary={summary}");
}
}
polymorphism
Polymorphism uses the derived method that matches the actual object.