Override the method during inheritance - CSharp Custom Type

CSharp examples for Custom Type:Inheritance

Description

Override the method during inheritance

Demo Code

using System;//from w w  w  .  j a  v a 2  s .c o m
public class Dog {

   public string Name;
   public int    Weight;

   public virtual void Speak( ) { 
      Console.WriteLine("ruff!"); 
   }
   public void DrinkWater( ) { 
      Console.WriteLine("Gulp"); 
   }
}

public class GermanShepard : Dog {
   public void OnGuard( ) { Console.WriteLine("In Guard Mode"); }
   //override the Dog.Speak() method
   public override void Speak( ) { Console.WriteLine("RUFF,RUFF,RUFF"); }
}
public class JackRussell : Dog {
   public void Chew( ) { Console.WriteLine("I'm chewing your favorite shoes!"); }
   //override the Dog.Speak() method
   public override void Speak( ) { Console.WriteLine("yap,yap,yap"); }
}
public class Inherit {
   public static void Main( ) {
      GermanShepard A = new GermanShepard( );
      JackRussell Daisy   = new JackRussell( );
      A.Name = "A"; A.Weight = 85;
      Daisy.Name = "Daisy"; Daisy.Weight = 25;
      Dog d = A;
      d.Speak( );      //calls GermanShepard.Speak( );
      d = Daisy;
      d.Speak( );      //calls JackRussell.Speak( );
   }
}

Result


Related Tutorials