CSharp – Inheritance

Inheritance (Ereditarietà) allows us to define a class in terms of another class, which makes it easier to create and maintain an application.

When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.

The derived class inherits the base class member variables and member methods.

Syntax


<acess-specifier> class <base_class>
{
 ...
}
class <derived_class> : <base_class>
{
 ...
}

Example


using System;
namespace InheritanceApplication
{
   // Base Class
   class Shape 
   {
      public void setWidth(int w)
      {
         width = w;
      }
      public void setHeight(int h)
      {
         height = h;
      }
      protected int width;
      protected int height;
   }

   // Derived class
   class Rectangle: Shape
   {
      public int getArea()
      { 
         return (width * height); 
      }
   }
   
   class RectangleTester
   {
      static void Main(string[] args)
      {
         Rectangle Rect = new Rectangle(); // Declare Rect of type Rectangle

         Rect.setWidth(5);
         Rect.setHeight(7);

         // Print the area of the object.
         Console.WriteLine("Total area: {0}",  Rect.getArea());
         Console.ReadKey();
      }
   }
}

The result is:

Total area: 35

For italian people: come funziona?
1. la funzine Main() è la prima ad essere eseguita
2. Rectangle Rect = new Rectangle(); -> dichiaro Rect di tipo classe Rectangle
3. Rect.setWidth(5); -> invio alla classe Rectangle, funzione setWidth() il valore 5
4. la funzione setWidth() è stata ereditata dalla classe Shape, infatti…
5. class Rectangle: Shape -> la classe Rectangle è derivata dalla classe base Shape dalla quale ne eredita le funzioni
6. Rect.setHeight(7); -> come per il punto 4. e 5. viene settata la variabile height = h;
7. Rect.getArea() -> calcola l’area -> return (width * height);

I vantaggi che porta una struttura che utilizza l’ereditarietà delle classi è che il codice risulta più facile da mantenere e modificare rispetto ad una struttura con una singola classe. Ovviamente tutto questo ha senso se il nostro codice necessita di classi complesse, non di una struttura semplice come quella riportata nell’esempio sopra.

My website: http://www.lucedigitale.com

Ref: http://www.tutorialspoint.com/csharp/csharp_inheritance.htm