Create Bicycle class With Accessor Methods - CSharp Custom Type

CSharp examples for Custom Type:Field

Description

Create Bicycle class With Accessor Methods

Demo Code

using System;/*from  w  w  w  .  j  a va  2  s.co m*/
class Bicycle
{
   const byte MaxSpeed = 40;
   private byte speed = 0;
   private int speedAccessCounter = 0;
   public byte GetSpeed()
   {
      speedAccessCounter++;
      return speed;
   }
   public void SetSpeed(byte newSpeed)
   {
      if (newSpeed > MaxSpeed)
         Console.WriteLine("Error. {0} exceeds the speed limit {1}", newSpeed, MaxSpeed);
      else if (newSpeed < 0)
          Console.WriteLine("Error. {0} is less than 0", newSpeed);
      else
         speed = newSpeed;
   }
   public int GetSpeedAccessCounter()
   {
         return speedAccessCounter;
   }
}
class BicycleTester
{
      public static void Main()
      {
         byte speedInMilesPerHour;
         Bicycle myBike = new Bicycle();
         myBike.SetSpeed(60);
         myBike.SetSpeed(30);
         Console.WriteLine("Current speed of myBike: {0}", myBike.GetSpeed());
         speedInMilesPerHour = (byte)(myBike.GetSpeed () * 0.621);
         Console.WriteLine("Number of times speed of myBike has been retrieved: {0}", myBike.GetSpeedAccessCounter());
      }
}

Result


Related Tutorials