Advertisement
karlakmkj

Inheritance using base()

Nov 25th, 2020
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.80 KB | None | 0 0
  1. //In Vehicle.cs file
  2. using System;
  3.  
  4. namespace LearnInheritance
  5. {
  6.   class Vehicle
  7.   {
  8.     public Vehicle (double speed){
  9.       this.Speed = speed;
  10.       LicensePlate = Tools.GenerateLicensePlate();
  11.     }
  12.  
  13.     public string LicensePlate
  14.     { get; private set; }   //Since the LicensePlate and Speed properties defined in Vehicle are no longer accessed in Sedan or Truck, they no longer need to be protected. Switch those two setters to private.
  15.  
  16.     public double Speed
  17.     { get; private set; }
  18.  
  19.     public int Wheels
  20.     { get; protected set; }
  21.  
  22.     public void SpeedUp()
  23.     {
  24.       Speed += 5;
  25.     }
  26.  
  27.     public void SlowDown()
  28.     {
  29.       Speed -= 5;
  30.     }
  31.    
  32.     public void Honk()
  33.     {
  34.       Console.WriteLine("HONK!");
  35.     }
  36.  
  37.   }
  38. }
  39. ============================================================================================================================
  40. //In Sedan.cs file
  41. using System;
  42.  
  43. namespace LearnInheritance
  44. {
  45.   class Sedan : Vehicle, IAutomobile
  46.   {
  47.     public Sedan(double speed) :base(speed)  //inherit parent constructor with the same one argument - speed
  48.     {
  49.      //hence no need set values for Speed and LicensePlate here
  50.       Wheels = 4;
  51.     }
  52.   }
  53. }
  54. ============================================================================================================================
  55. //In Truck.cs file
  56. using System;
  57.  
  58. namespace LearnInheritance
  59. {
  60.   class Truck : Vehicle, IAutomobile
  61.   {
  62.     public double Weight
  63.     { get; }
  64.  
  65.     public Truck(double speed, double weight): base(speed) //also inherit parent constructor
  66.     {
  67.       //also no need set values for Speed and LicensePlate here
  68.       Weight = weight;
  69.  
  70.       if (weight < 400)
  71.       {
  72.         Wheels = 8;
  73.       }
  74.       else
  75.       {
  76.         Wheels = 12;
  77.       }
  78.     }
  79.  
  80.   }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement