Chapter 8. 面向对象(多态--抽象类)

本文通过具体的C#代码示例介绍了抽象类和多态的概念。首先定义了抽象类Animal及其抽象方法Bark(),并通过派生类dog和cat实现不同动物叫声的具体行为。随后介绍了形状抽象类Shape及其抽象方法GetArea()和GetPerimeter(),并展示了如何通过Circle和Square类实现计算圆形和矩形的面积与周长。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 抽象类
{
    class Program
    {
        static void Main(string[] args)
        {
            //狗狗会叫,猫咪也会叫
            Animal a = new dog();
            a.Bark();
            Console.ReadLine();
       Animal aa
= new cat(); aa.Bark(); Console.ReadLine();
        
//使用多态求矩形和圆形的面积和周长 Shape shape = new Circle(5); double area = shape.GetArea(); double perimeter = shape.GetPerimeter(); Console.WriteLine("面积是{0},周长是{1}", area, perimeter); Console.ReadLine();
         Shape shape1
= new Square(10,20); double area1 = shape1.GetArea(); double perimeter1 = shape1.GetPerimeter(); Console.WriteLine("面积是{0},周长是{1}",area1,perimeter1); Console.ReadLine();
         }
public abstract class Animal //抽象类 { public abstract void Bark(); //抽象方法 } public class dog : Animal { public override void Bark() { Console.WriteLine("狗狗旺旺的叫"); } } public class cat : Animal { public override void Bark() { Console.WriteLine("猫咪喵喵的叫"); } } public abstract class Shape //抽象类 { public abstract double GetArea(); //抽象方法 public abstract double GetPerimeter(); } public class Circle : Shape  //圆形类 { private double _r; public double R { get { return _r; } set { _r = value; } } public Circle(double r) { this.R = r; } public override double GetArea() { return Math.PI * this.R * this.R; } public override double GetPerimeter() { return 2 * Math.PI * this.R; } } public class Square : Shape //矩形类 { private double _height; public double Height { get { return _height; } set { _height = value; } } private double _width; public double Width { get { return _width; } set { _width = value; } } public Square(double height, double width) { this.Height = height; this.Width = width; } public override double GetArea() { return this.Height * this.Width; } public override double GetPerimeter() { return 2 * (this.Height + this.Width); } } } }

 

转载于:https://www.cnblogs.com/xiao55/p/5598375.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值