Advertisement
svetoslavbozov

[OOP] Fundamental Principles Part II - Задача 1

Mar 6th, 2013
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.02 KB | None | 0 0
  1. using System;
  2.  
  3. class Polymorphism
  4. {
  5.     static void Main(string[] args)
  6.     {
  7.         Shape[] figures = new Shape[]
  8.         {
  9.             new Rectangle(3,3),
  10.             new Circle(2),
  11.             new Rectangle(2,3),
  12.             new Circle(5),
  13.             new Triangle(5,7),
  14.             new Triangle(2,3)
  15.         };
  16.  
  17.         foreach (Shape figure in figures)
  18.         {
  19.             Console.WriteLine("Figure = {0} surface = {1:F2}",
  20.                 figure.GetType().Name.PadRight(9, ' '),
  21.                 figure.CalculateSurface());
  22.         }
  23.     }
  24. }
  25. public abstract class Shape
  26. {
  27.     private int width;
  28.     private int height;
  29.  
  30.     public int Width
  31.     {
  32.         get { return this.width; }
  33.         set
  34.         {
  35.             if (this.width < 0)
  36.             {
  37.                 throw new ArgumentOutOfRangeException();
  38.             }
  39.             this.width = value;
  40.         }        
  41.     }
  42.     public int Height
  43.     {
  44.         get { return this.height; }
  45.         set
  46.         {
  47.             if (this.height < 0)
  48.             {
  49.                 throw new ArgumentOutOfRangeException();
  50.             }
  51.             this.height = value;
  52.         }
  53.     }
  54.  
  55.     public Shape(int width, int height)
  56.     {
  57.         this.Width = width;
  58.         this.Height = height;
  59.     }
  60.  
  61.     public abstract double CalculateSurface();
  62. }
  63. public class Triangle : Shape
  64. {
  65.     public Triangle(int width, int height)
  66.         : base(width, height)
  67.     {
  68.     }
  69.  
  70.     public override double CalculateSurface()
  71.     {
  72.         return this.Width * this.Height / 2;
  73.     }
  74. }
  75. public class Rectangle : Shape
  76. {
  77.     public Rectangle(int width, int height)
  78.         : base(width, height)
  79.     {
  80.     }
  81.  
  82.     public override double CalculateSurface()
  83.     {
  84.         return this.Width * this.Height;
  85.     }
  86. }
  87. public class Circle : Shape
  88. {
  89.     public Circle(int radius)
  90.         : base(radius, height: radius)
  91.     {
  92.     }
  93.     public override double CalculateSurface()
  94.     {
  95.         return Math.PI * this.Width * this.Width;
  96.     }
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement