**
使用抽象函数abstract
作者:秋名
撰写时间:2020 年05 月23日
多态的作用: 把不同的子类对象当作父类来看,可以屏蔽不同子类对象之间的差异,写出通用的代码,做出通用的编程,以适应需求的不断变化**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _抽象类实现多态案例
{
class Program
{
//开发当中,尽量用抽象,不要用具体。能用父类就不用子类。能用抽象的父类就不用具体的父类。能用接口,就不用抽象
static void Main(string[] args)
{
#region 抽象案例一
//Student s = new Student();
//Person p = new Student();
//p.SayHi();
//p.Standup();
//Person T = new Teacher();
//T.SayHi();
//T.Standup();
#endregion
#region 抽象案例二
//练习1:动物Animal 都吃Eat的方法和Bark()叫,狗Dog和猫Cat叫的方法都不一样,父类中没有默认的实现,所以考虑用抽象方法。
//Animal D = new Dog();
//D.Eat();
//D.Bark();
//Animal C = new Cat();
//C.Eat();
//C.Bark();
//练习2:计算形状Shape(圆Circle,矩形Square,正方形Rectangle)的面积、周长
//圆的周长=圆周率×直径 公式:c=πd =2πr
//圆的面积=半径×半径×π 公式:S=πrr
//矩形的周长=2*(长+宽)公式:L=2(a+b)
//矩形的面积 =长*宽 公式:S=a×b
//正方形的周长 = 边长×4
//正方形的面积 = 边长×边长
Shape shape = new Rectangle(40);//new Square(100, 20); //new Circle(20);
Console.WriteLine("周长:{0}",shape.Girth());
Console.WriteLine("面积:{0}",shape.Area());
#endregion
Console.ReadKey();
}
}
#region 抽象案例1
//抽象父类
abstract class Person
{
public abstract void SayHi();
public abstract void Standup();
}
//抽象学生类
class Student : Person
{
public override void SayHi()
{
Console.WriteLine("我是学生。");
}
public override void Standup()
{
Console.WriteLine("一位好学生");
}
}
//抽象教师
class Teacher : Person
{
public override void SayHi()
{
Console.WriteLine("我是老师,");
}
public override void Standup()
{
Console.WriteLine("一位好老师");
}
}
#endregion
#region 抽象案例2—练习一
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("喵喵喵!");
}
}
#endregion
#region 抽象案例2—练习二
abstract class Shape
{
public abstract double Area();//面积
public abstract double Girth();//周长
}
//定义圆的类(求周长和面积)
class Circle : Shape
{
public Circle(double r)
{
this.R = r;
}
public double R { get; set; }
public override double Area()
{
return Math.PI * this.R * this.R;
}
public override double Girth()
{
return 2 * Math.PI * this.R;
}
}
//定义矩形的类(求周长和面积)
class Square : Shape
{
public Square(double length, double Width)
{
this.length = length;
this.Width = Width;
}
public double length { get; set;}
public double Width { get; set; }
public override double Area()
{
return length * Width;
}
public override double Girth()
{
return (length + Width) * 2;
}
}
//定义正方形的类(求周长和面积)
class Rectangle:Shape
{
public double Bian { get; set;}
public Rectangle(double Bian)
{
this.Bian = Bian;
}
public override double Area()
{
return Bian * Bian;
}
public override double Girth()
{
return Bian * 4;
}
}
#endregion
}