c# 虚函数 ,抽象类

时间:2021-09-08 05:08:38
---抽象类
class Program
{
static void Main(string[] args)
{
Rectangle r = new Rectangle(, );
double a = r.area();
Console.WriteLine("面积: {0}", a);
Console.ReadKey();
}
}
abstract class Shape
{
abstract public int area();
}
class Rectangle : Shape
{
private int length;
private int width;
public Rectangle(int a = , int b = )
{
length = a;
width = b;
}
public override int area()
{
Console.WriteLine("Rectangle 类的面积:");
return (width * length);
}
}
----虚函数 class Shape
{
protected int width, height;
public Shape(int a = , int b = )
{
width = a;
height = b;
}
public virtual int area()
{
Console.WriteLine("父类的面积:");
return ;
}
}
class Rectangle : Shape
{
public Rectangle(int a = , int b = )
: base(a, b)
{ }
public override int area()
{
Console.WriteLine("Rectangle 类的面积:");
return (width * height);
}
}
class Triangle : Shape
{
public Triangle(int a = , int b = )
: base(a, b)
{ }
public override int area()
{
Console.WriteLine("Triangle 类的面积:");
return (width * height / );
}
}
class Caller
{
public void CallArea(Shape sh)
{
int a;
a = sh.area();
Console.WriteLine("面积: {0}", a);
}
}
class Tester
{ static void Main(string[] args)
{
Caller c = new Caller();
Rectangle r = new Rectangle(, );
Triangle t = new Triangle(, );
c.CallArea(r);
c.CallArea(t);
Console.ReadKey();
}
}

1.virtual:允许被重写,但不强制要求。声明时提供其自身实现;
2.abstract:强制要求其继承者重写。声明时不提供其自身的实现,抽象类不能被实例化;
3.interface:接口就是协议,其声明的成员(属性,方法,事件和索引器)必须由其继承的类实现。接口不能直接被实例化。

虚方法与抽象方法的区别在于,虚方法提供自身的实现,并不强制要求子类重写;而抽象方法不提供自身的实现,并且强制子类重写。

抽象类与接口
很相似,但是思路不一样。接口是公开类的成员,而抽象类则是抽象类成员以要求子类继承并实现。
相同点:1、都不能实例化;
2、都包含未实现的方法声明
不同:1、抽象类只有抽象方法,接口可以包含方法、属性、索引器、事件