Advertisement
karlakmkj

Inheritance - override & virtual

Nov 25th, 2020
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.29 KB | None | 0 0
  1. //In Bicycle.cs file
  2. using System;
  3.  
  4. namespace LearnInheritance
  5. {
  6.   class Bicycle : Vehicle {
  7.     public Bicycle(double Speed): base(Speed){
  8.       Wheels =2;
  9.     }
  10.  
  11.     //use override keyword to override parent/superclass methods
  12.     public override void SpeedUp(){
  13.       Speed +=5;
  14.       if (Speed >15) {
  15.          Speed = 15;
  16.       }
  17.     }
  18.     public override void SlowDown(){
  19.       Speed -=5;
  20.       if (Speed<0){
  21.         Speed =0;
  22.       }
  23.     }
  24.  
  25.   }
  26. }
  27. ============================================================================================================================
  28. //In Vehicle.cs file
  29. using System;
  30.  
  31. namespace LearnInheritance
  32. {
  33.   class Vehicle
  34.   {
  35.     public string LicensePlate
  36.     { get; private set; }
  37.  
  38.     public double Speed
  39.     { get; protected set; }
  40.  
  41.     public int Wheels
  42.     { get; protected set; }
  43.  
  44.     public Vehicle(double speed)
  45.     {
  46.       Speed = speed;
  47.       LicensePlate = Tools.GenerateLicensePlate();
  48.     }
  49.  
  50.     //mark the methods with virtual keyword so as to allow child/subclass to override it
  51.     public virtual void SpeedUp()
  52.     {
  53.       Speed += 5;
  54.     }
  55.  
  56.     public virtual void SlowDown()
  57.     {
  58.       Speed -= 5;
  59.     }
  60.    
  61.     public void Honk()
  62.     {
  63.       Console.WriteLine("HONK!");
  64.     }
  65.  
  66.   }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement