---------------------- ASP.Net+Android+IO开发S、.Net培训、期待与您交流! ----------------------
1.抽象成员必须标记为abstract,并且不能有任何实现。
2.抽象成员必须在抽象类中。3.抽象类不能被实例化
4.子类继承抽象类后,必须把父类中的所有抽象成员都重写。
(除非子类也是一个抽象类,则可以不重写)
5.抽象成员的访问修饰符不能是private
6.在抽象类中可以包含实例成员。
并且抽象类的实例成员可以不被子类实现
7、抽象类中可以写构造函数,但是没有意义,因为抽象类不能被实例化,也就是不能new,也就调用不到构造函数
8、如果父类的抽象方法中有参数,那么。继承这个抽象父类的子类在重写父类的方法的时候必须传入对应的参数。
如果抽象父类的抽象方法中有返回值,那么子类在重写这个抽象方法的时候 也必须要传入返回值。
======
如果父类中的方法有默认的实现,并且父类需要被实例化,这时可以考虑将父类定义成一个普通类,用虚方法来实现多态。
如果父类中的方法没有默认实现,父类也不需要被实例化,则可以将该类定义为抽象类。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _09抽象类练习
{
class Program
{
static void Main(string[] args)
{
//计算 圆形和矩形的面积 、周长 用多态来实现
Shape shape = new Square(5, 8);//new Circle(1.5);
double area = shape.GetArea();
double perimeter = shape.GetPerimeter();
Console.WriteLine("这个形状的面积是{0:0.00},周长是{1:0.00}",area,perimeter);
Console.ReadKey();
}
}
public abstract class Shape
{
public abstract double GetArea();
public abstract double GetPerimeter();
}
public class Circle : Shape
{
public double R
{
get;
set;
}
public Circle(double r)
{
this.R = r;
}
/// <summary>
/// 计算圆的面积
/// </summary>
/// <returns></returns>
public override double GetArea()
{
return Math.PI * this.R * this.R;
}
/// <summary>
/// 计算圆的周长
/// </summary>
/// <returns></returns>
public override double GetPerimeter()
{
return 2 * Math.PI * this.R;
}
}
public class Square : Shape
{
public double Height
{
get;
set;
}
public double Width
{
get;
set;
}
public Square(double heigth, double width)
{
this.Height = heigth;
this.Width = width;
}
/// <summary>
/// 计算矩形的面积
/// </summary>
/// <returns></returns>
public override double GetArea()
{
return this.Height * this.Width;
}
/// <summary>
/// 计算矩形的周长
/// </summary>
/// <returns></returns>
public override double GetPerimeter()
{
return (this.Height + this.Width) * 2;
}
}
}
---------------------- ASP.Net+Android+IO开发S、.Net培训、期待与您交流! ----------------------