先定义一个抽象类shape,用abstract修饰
abstract class shape
{
private double width;
private double height;
protected shape(double width, double height)
{
this.width = width;
this.height = height;
}
//虚函数
public abstract double getArea();
public double Width { get => width; set => width = value; }
public double Height { get => height; set => height = value; }
}
然后定义一个Rectangle类继承shape类,在类中实现shape的虚函数getArea()
class Rectangle : shape
{
//提供shape所需的形参
public Rectangle(double width,double height):base(width,height)
{
this.Width = width;
this.Height = height;
}
//实现shape类中的抽象函数
public override double getArea()
{
return this.Height * this.Width;
}
}
本文介绍了如何定义一个抽象类Shape,其中包含私有变量和保护构造函数,以及一个抽象方法getArea()。接着,我们展示了Rectangle类如何继承Shape,并重写getArea()方法,用于计算矩形面积。

2578

被折叠的 条评论
为什么被折叠?



