Thursday, November 20, 2008

Inheritance

There are two kinds of inheritance

1. Implementation inheritance

2.Interface inheritance

Structs can not be derived from classes, they are always derived from System.ValueType.

A class cannot inheritate from multiple classes but can inherit from a class and multiple interfaces, c# is known as single inheritance programming language

When a derived class inherits from a base class, it gains all the methods, fields, properties and events of the base class. To change the data and behavior of a base class, you have two choices: you can replace the base member with a new derived member, or you can override a virtual base member.

If the method in the derived class is not preceded by new or override keywords, the compiler will issue a warning and the method will behave as if the new keyword were present

The base class method can be called from within the derived class using the base keyword.

   1: public class BaseClass
   2: {
   3:     public virtual void Test()
   4:     {
   5:         Console.WriteLine("Base");
   6:     }
   7:  
   8: }
   9: public class AClass : BaseClass
  10: {
  11:         public new void Test()
  12:         {
  13:             Console.WriteLine("AClass");
  14:         }
  15: }
  16: public class BClass : BaseClass
  17: {
  18:     public override void Test()
  19:     {
  20:         Console.WriteLine("BClass");
  21:     }
  22: }
  23: class Program
  24: {
  25:  
  26:     static void Main(string[] args)
  27:     {
  28:  
  29:         BaseClass basev = new BaseClass();
  30:         basev.Test();
  31:         BaseClass aclass = new AClass();
  32:         aclass.Test();
  33:         BaseClass bClass = new BClass();
  34:         bClass.Test();
  35:         Console.Read();
  36:  
  37:     }
  38: }