jyoung12387

Abstract Class Example

Mar 22nd, 2020
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.67 KB | None | 0 0
  1. using System;
  2.  
  3. namespace abstractClassExample
  4. {
  5.     class Program
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             Shape[] shapes = { new Sphere(4), new Cube(3) };
  10.  
  11.             foreach(Shape shape in shapes)
  12.             {
  13.                 shape.GetInfo();
  14.                 Console.WriteLine($"{shape.Name} has a volume of {shape.Volume()}\n");
  15.             }
  16.  
  17.             Console.ReadLine();
  18.  
  19.         }
  20.     }
  21.  
  22.     abstract class Shape
  23.     {
  24.         public string Name { get; set; }
  25.  
  26.         public virtual void GetInfo()
  27.         {
  28.             Console.WriteLine($"This is a {Name}");
  29.         }
  30.  
  31.         // Only declaring the method, not implementing it
  32.         public abstract double Volume();
  33.  
  34.     }
  35.  
  36.     class Cube : Shape
  37.     {
  38.         public double Length { get; set; }
  39.  
  40.         public Cube(double length)
  41.         {
  42.             Name = "Cube";
  43.             Length = length;
  44.         }
  45.  
  46.         public override double Volume()
  47.         {
  48.             return Math.Pow(Length, 3);
  49.         }
  50.  
  51.         public override void GetInfo()
  52.         {
  53.             base.GetInfo();
  54.             Console.WriteLine($"The Cube has a length of {Length}");
  55.         }
  56.    
  57.     class Sphere : Shape
  58.     {
  59.         public double Radius { get; set; }
  60.  
  61.         public Sphere(double radius)
  62.         {
  63.             Name = "Sphere";
  64.             Radius = radius;
  65.         }
  66.         public override double Volume()
  67.         {
  68.             return Math.PI * (Math.Pow(Radius, 3)) * 4 / 3;
  69.         }
  70.  
  71.         public override void GetInfo()
  72.         {
  73.             base.GetInfo();
  74.             Console.WriteLine($"The Cube has a radius of {Radius}");
  75.         }
  76.     }
  77. }
Add Comment
Please, Sign In to add comment