抽象方法 抽象类 (abstract)
1.抽象方法 abstract , 不提供方法实现内容!
2. 包含抽象方法的一定是抽象类! 但抽象类不一定要有抽象方法!
3. 抽象方法 强制要求 所有派生类必须重载它!
4. 对抽象类 无法创建其实例! 只有通过其派生类的实例。
5. 如果抽象类中定义了抽象方法,那么其所有派生类必须继承这些抽象方法。
并且其派生类若不是抽象类的时候,还必须重载实现这些抽象方法。(重载还用override ,但不用virtual)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApp { class AbstractInheritSample { static void Main(string[] args) { //实例数组 Shape[] shapes = new Shape[8]; for (int i = 0; i < 4; i++) { shapes[i] = new Circle(i + 1); shapes[4 + i] = new Rectangle(i + 2, i + 4); } foreach (Shape s in shapes) { Console.WriteLine("{0}:周长{1},面积{2}", s, s.Perimeter, s.Area); } Console.Read(); } } //抽象类 public abstract class Shape { public abstract double Perimeter { get; } public abstract double Area { get; } } //派生类 public class Circle : Shape { private double m_radius; public override double Perimeter { get { return 6.28 * m_radius; } } public override double Area { get { return 3.14 * m_radius * m_radius; } } public Circle(double radius) { m_radius = radius; } //重载Object类的虚拟方法ToString public override string ToString() { return string.Format("圆形(半径{0})", m_radius); } } //派生类:矩形Rectangle public class Rectangle : Shape { private double m_side1; private double m_side2; public override double Perimeter { get { return (2 * m_side1 + 2 * m_side2); } } public override double Area { get { return m_side1 * m_side2; } } public Rectangle(double side1, double side2) { m_side1 = side1; m_side2 = side2; } public override string ToString() { return string.Format("矩形(边长{0},{1})", m_side1, m_side2); } } }