c# 设计一个类shape(抽象的),设计其两个子类,circle(圆形)类和square(正方形)类。利用多态实现
发布网友
发布时间:2022-05-10 18:37
我来回答
共4个回答
热心网友
时间:2023-10-22 05:31
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Shape[] shapes = new Shape[10];
for (int i = 0; i < 10; i++)
{
Random r = new Random();
if (i % 2 == 0)
{
shapes[i] = new Circle(r.NextDouble() * 10);
}
else {
shapes[i] = new Square(r.NextDouble() * 10);
}
shapes[i].Area();
shapes[i].Girth();
}
Console.ReadLine();
}
}
public abstract class Shape
{
//求面积
public abstract void Area();
//求周长
public abstract void Girth();
}
public class Circle : Shape
{
public const double Pi = 3.14;
//半径
public double R = 0.00;
public Circle(double r)
{
this.R = r;
Console.WriteLine("该形状是圆形.它的半径为:{0}",R);
}
public override void Area()
{
double area = Pi * R * R;
Console.WriteLine("圆的面积为:{0}",area);
}
public override void Girth()
{
double girth = 2 * Pi * R;
Console.WriteLine("圆的周长为:{0}", girth);
}
}
public class Square : Shape
{
//边长
public double L = 0.00;
public Square(double l)
{
this.L = l;
Console.WriteLine("该形状是正方形.它的边长为:{0}",L);
}
public override void Area()
{
double area = L * L;
Console.WriteLine("正方形的面积为:{0}", area);
}
public override void Girth()
{
double girth = 4 * L;
Console.WriteLine("正方形的周长为:{0}", girth);
}
}
}
热心网友
时间:2023-10-22 05:31
你要把方法写在抽象的父类中才行
愿你成功
热心网友
时间:2023-10-22 05:32
using System;
namespace Demo {
public abstract Shape {
public abstract double CalcArea();
}
public Circle : Shape {
private double r;
public Circle(double r) {
this.r = r;
}
public override double CalcArea() {
return Math.PI*Math.Pow(r,2);
}
}
public Square : Shape {
private double a;
public Square(double a) {
this.a = a;
}
public override double CalcArea() {
return Math.Pow(a,2);
}
}
}
热心网友
时间:2023-10-22 05:33
嘿嘿,不懂