c#基础学习(0709)之vs通过抽象方法实现多态

抽象类不能用来实例化对象

1、抽象类中可以有实例成员,也可以有抽象成员

2、抽象成员不能有任何实现

3、抽象类、抽象成员必须包含在抽象类中

4、抽象类不能用来实例化对象,既然抽象类不能被实例化,那么抽象类的作用就是用来被继承的,继承的主要目的就是用来实现多态

5、抽象成员子类继承以后必须“重写”,override,除非子类也是个抽象类

namespace 抽象类实现多态案例
{
    class Class1
    {
        static void Main(string[] args)
        {
            //例子一
            Animal animal = new Dog();
            animal.Eat();
            animal.Bark();
            Console.ReadKey();

            //例子二
            Shape shape = new Rectangle(100, 20);//new Circle(20);
            Console.WriteLine("周长:{0}", shape.GetGirth());
            Console.WriteLine("面积:{0}",shape.GetArea());
            Console.ReadKey();
        }
    }
    
    abstract class Shape
    {
        public abstract double GetArea();
        public abstract double GetGirth();
    }
    class Circle : Shape
    {
        public Circle(double r)
        {
            this.R = r;
        }
        public double R { get; set; }
        public override double GetArea()
        {
            return Math.PI * this.R * this.R;
        }
        public override double GetGirth()
        {
            return 2 * Math.PI * this.R;
        }
    }
    class Rectangle:Shape
    {
        public Rectangle(double length,double width)
        {
            this.Length = length;
            this.Width = width;
        }
        public double Length { get; set; }
        public double Width { get; set; }
        public override double GetArea()
        {
            return Length * Width;
        }
        public override double GetGirth()
        {
            return 2 * (Length + Width);
        }
    }

    //========================================

    abstract class Animal
    {
        public abstract void Eat();
        public abstract void Bark();
    }
    class Dog : Animal
    {
        public override void Eat()
        {
            Console.WriteLine("狗吃骨头");
        }
        public override void Bark()
        {
            Console.WriteLine("汪汪汪");
        }
    }
    class Cat : Animal
    {
        public override void Eat()
        {
            Console.WriteLine("毛吃鱼");
        }
        public override void Bark()
        {
            Console.WriteLine("喵喵喵");
        }
    }
}

什么时候使用抽象类

1、是不是需要被实例化

2、父类中有没有默认的实现

如果不需要被实例化,父类中没有默认的实现,则用抽象类,否则用虚方法来实现

猜你喜欢

转载自www.cnblogs.com/chao202426/p/9284682.html
今日推荐