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

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); } } } }

 

posted @ 2016-06-19 17:06  庚xiao午  阅读(164)  评论(0编辑  收藏  举报